Hi, can anybody help me understand how does compos...
# compose
d
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
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
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
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
maybe it injiects into setValue(), somehow
a
d
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
so when i do val foo: String by l.oserveAsState("")
is foo a snapshot-backed-object ?
a
yes
d
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
ooohh
ok
thank you
👍 1