|
|
|
|
|
by olcay_
102 days ago
|
|
I think Jetpack Compose is not actually as bad as you think. I think it's really great and I wish more people caught on actually. I can't comment on the learning materials as I was following it since the project started and I was already accustomed to the Android Developers website. Kotlin has a few reactiveness concepts that make reactivity easier but might scare off developers from other languages. The most important ones are Flows and Coroutines. Say you want to have a UI that shows the current list of connected devices that should always show up to date info. The function to get the list would be something like this: val devices = manager.getDevices()
But you need it to be declarative instead of imperative, so you use a Flow: val devices = flow {
while(true) {
emit(manager.getDevices())
delay(1000)
}
}
Devices is now a cold flow. It does nothing unless it's being collected. When you start collecting it, e.g. by using collect: devices.collect { list -> ... }
Now it starts running the while loop and you get the up to date devices list in your lambda every second. You can also make the lambda run only when the list has changed, or debounce it, or run only for the latest value, and more with trivial function chaining.
But this function is suspending, which is Kotlin's way of async functions, and suspend functions take turns running on the threads that are managed by the coroutine scope they are in, so you need to provide it a coroutine scope by wrapping your collection in scope.launch { ... } .And your viewmodel can now collect the flow in a way that's going to be accessible without suspending (async) functions by turning it into a StateFlow: val devicesStateFlow: StateFlow<List<Device>> = devicesFlow.stateIn(scope, some more arguments...)
// Now synchronous code can call like this:
print(devicesStateFlow.value)
// And Compose (reactive ui) code can do this in Composable functions:
val devicesState by vm.devicesStateFlow.collectAsState()
I think that was the source of confusion you had when you were trying to use datastore. It's designed for reactive applications so you were supposed to use it in a viewmodel, turn it into a stateflow and collect it as state in your ui. |
|