RxJava integration
To use the disposables and RxScreenModel you should first import cafe.adriel.voyager:voyager-rxjava (see Setup).

CompositeDisposable

The ScreenModel provides a disposables property. It's cleared automatically when the ScreenModel is disposed.
1
class PostDetailsScreenModel(
2
private val repository: PostRepository
3
) : ScreenModel {
4
5
fun getPost(id: String) {
6
repository.getPost(id)
7
.subscribe { post -> /* ... */ }
8
.let(disposables::add)
9
}
10
}
Copied!

State-aware ScreenModel

If your ScreenModel needs to provide a state, use the RxScreenModel. Use mutableState to change the current state.
1
class PostDetailsScreenModel(
2
private val repository: PostRepository
3
) : RxScreenModel<PostDetailsScreenModel.State>() {
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
repository.getPost(id)
13
.doOnSubscribe { mutableState.onNext(State.Loading) }
14
.subscribe { post -> mutableState.onNext(State.Result(post)) }
15
.let(disposables::add)
16
}
17
}
Copied!
In your screen use state.subscribeAsState() 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.subscribeAsState(initial = State.Init)
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