Coroutines integration
The coroutineScope and StateScreenModelare part of the core library.

CoroutineScope

The ScreenModel provides a coroutineScope property. It's cancelled automatically when the ScreenModel is disposed.
1
class PostDetailsScreenModel(
2
private val repository: PostRepository
3
) : ScreenModel {
4
5
fun getPost(id: String) {
6
coroutineScope.launch {
7
val post = repository.getPost(id)
8
// ...
9
}
10
}
11
}
Copied!

State-aware ScreenModel

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.
1
class PostDetailsScreenModel(
2
private val repository: PostRepository
3
) : StateScreenModel<PostDetailsScreenModel.State>(State.Init) {
4
5
sealed class State {
6
object Init : State()
7
object Loading : State()
8
data class Result(val post: Post) : State()
9
}
10
11
fun getPost(id: String) {
12
coroutineScope.launch {
13
mutableState.value = State.Loading
14
mutableState.value = State.Result(post = repository.getPost(id))
15
}
16
}
17
}
Copied!
In your screen use state.collectAsState() and handle the current state.
1
class PostDetailsScreen : Screen {
2
3
@Composable
4
override fun Content() {
5
val screenModel = rememberScreenModel<PostDetailsScreenModel>()
6
val state by screenModel.state.collectAsState()
7
8
when (state) {
9
is State.Loading -> LoadingContent()
10
is State.Result -> PostContent(state.post)
11
}
12
}
13
}
Copied!

Sample

Sample code here.
Last modified 2mo ago