Coroutines integration
The
coroutineScope
and StateScreenModel
are part of the core library.The
ScreenModel
provides a coroutineScope
property. It's cancelled automatically when the ScreenModel
is disposed.class PostDetailsScreenModel(
private val repository: PostRepository
) : ScreenModel {
fun getPost(id: String) {
coroutineScope.launch {
val post = repository.getPost(id)
// ...
}
}
}
If your
ScreenModel
needs to provide a state, use the StateScreenModel
. Set the initial state on the constructor and use mutableState
to change the current state.class PostDetailsScreenModel(
private val repository: PostRepository
) : StateScreenModel<PostDetailsScreenModel.State>(State.Init) {
sealed class State {
object Init : State()
object Loading : State()
data class Result(val post: Post) : State()
}
fun getPost(id: String) {
coroutineScope.launch {
mutableState.value = State.Loading
mutableState.value = State.Result(post = repository.getPost(id))
}
}
}
In your screen use
state.collectAsState()
and handle the current state.class PostDetailsScreen : Screen {
@Composable
override fun Content() {
val screenModel = rememberScreenModel<PostDetailsScreenModel>()
val state by screenModel.state.collectAsState()
when (state) {
is State.Loading -> LoadingContent()
is State.Result -> PostContent(state.post)
}
}
}
Last modified 11mo ago