LiveData integration
To use the LiveScreenModel you should first import cafe.adriel.voyager:voyager-livedata (see Setup).

State-aware ScreenModel

If your ScreenModel needs to provide a state, use the LiveScreenModel. Set the initial state on the constructor and use mutableState to change the current state.
1
class PostDetailsScreenModel(
2
private val repository: PostRepository
3
) : LiveScreenModel<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
val result = State.Result(post = repository.getPost(id))
14
mutableState.postValue(result)
15
}
16
}
17
}
Copied!
In your screen use state.observeAsState() 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.observeAsState()
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