https://kotlinlang.org logo
#compose
Title
# compose
d

Davide Bertola

11/29/2020, 3:02 PM
Hi, can anybody help me understand how does compose subscribe to state changes for knowing when to recompose ?
for example
liveObject.observeAsState()
returns a
State<T>
which is not something that can be subscribed to
b

Brandon Trautmann

11/29/2020, 3:15 PM
Specifically:
Note: observeAsState observes a LiveData<T> and returns a State<T> object that is updated whenever the LiveData changes. State<T> is an observable type that Jetpack Compose can use directly.
observeAsState will observe the LiveData only while it is in the Composition.
d

Davide Bertola

11/29/2020, 3:20 PM
yes i have read all of that and this is where i do not see anybody actually subscribing/observing
observeAsState internally subscribes, but it just returns a State<T>
so I am guessing there could be some compiler magic here ?
Copy code
@Composable
fun <R, T : R> LiveData<T>.observeAsState(initial: R): State<R> {
    val lifecycleOwner = LifecycleOwnerAmbient.current
    val observer = remember { DisposableObserver<R, T>(initial, lifecycleOwner) }
    observer.source = this
    return observer.state
}
h

Halil Ozercan

11/29/2020, 3:44 PM
I'd suggest this talk by LeLand. It helped me understand the basics behind compose-runtime and "compiler magic" that you referred. I'm not sure if there is any other up-to-date talk with the latest changes but I'd assume the basics stayed the same.

https://www.youtube.com/watch?v=Q9MtlmmN4Q0

d

Davide Bertola

11/29/2020, 3:45 PM
maybe it injiects into setValue(), somehow
a

Adam Powell

11/29/2020, 3:50 PM
d

Davide Bertola

11/29/2020, 3:53 PM
i'll try the video first as the conversation seems to start from some concepts I do not have in my mind
ok so the video does not really explain who and when triggers the recomposition
liveData.observe(this) { recompose() }
I would expect this somewhere if there was no compiler magic 🙂
snapshot observers observe all snapshot-backed objects in the process at once
it happens here:
Copy code
val unregisterApplyObserver = Snapshot.registerApplyObserver { changed, _ ->
    appliedChanges.offer(changed)
}
changed
is the set of snapshot-backed objects (e.g.
mutableStateOf
) that changed in a single transaction
d

Davide Bertola

11/29/2020, 4:47 PM
so when i do val foo: String by l.oserveAsState("")
is foo a snapshot-backed-object ?
a

Adam Powell

11/29/2020, 4:50 PM
yes
d

Davide Bertola

11/29/2020, 4:53 PM
that's what i have read in the first place
state.value = it
how do you know state has changed
(i am looking for the source of mutableStateOf() ) too see if the magic is there
d

Davide Bertola

11/29/2020, 4:58 PM
ooohh
ok
thank you
👍 1