Enrico Saggiorato
02/07/2022, 6:10 PMCasey Brooks
02/07/2022, 6:16 PMEnrico Saggiorato
02/07/2022, 6:22 PMremember
) in the application function instead of in one of my components, right?David W
02/07/2022, 6:40 PMapplication-wide state is just a regular state (called withnot necessarily even with) in the application function instead of in one of my components, right? (edited)remember
remember
, although you could do that. i think they just mean a variable that's accessible from anywhere in the applicationcompanion object { val appState: ... }
in your Application classCasey Brooks
02/07/2022, 6:48 PMFlow
is basically the Kotlin implementation of a reactive stream (like RxJava Observables), but built on coroutines. Compose is built on top of Coroutines as well, and integrates very nicely with Flows.
Here's a very simple example. See how the MyViewModel
is just a normal class, no super class necessary, and the "lifecycle" of the ViewModel is controlled by the composition, and you'd use it in much the same way as you would a normal Android ViewModel.
class MyViewModel(
val viewModelScope: CoroutineScope
) {
data class State(
val count: Int = 0
)
private val _state = MutableStateFlow(State())
val state: StateFlow<State> get() = _state.asStateFlow()
fun increment() {
viewModelScope.launch {
_state.update { it.copy(count = it.count + 1) }
}
}
fun decrement() {
viewModelScope.launch {
_state.update { it.copy(count = it.count - 1) }
}
}
}
@Composable
fun MyApp() {
val viewModelScope = rememberCoroutineScope()
val viewModel = remember(viewModelScope) { MyViewModel(viewModelScope) }
val vmState by viewModel.state.collectAsState()
MyAppUi(
state = vmState,
onIncrement = { viewModel.increment() },
onDecrement = { viewModel.decrement() },
)
}
@Composable
fun MyAppUi(
state: MyViewModel.State,
onIncrement: ()->Unit,
onDecrement: ()->Unit,
) {
// ...
}
gildor
02/10/2022, 11:57 PMDavid W
02/10/2022, 11:59 PMgildor
02/11/2022, 12:01 AM