ursus
12/02/2021, 2:26 PMclass Syncer {
private val scope = CoroutineScope(SupervisorJob() + <http://Dispatcher.Io|Dispatcher.Io>)
private val _state = MutableStateFlow<State>(Idle)
val state: Flow<State> get() = _state
fun sync() {
scope.launch {
_state.value = Syncing
someSuspendingApiAndDbStuff()
_state.value = Synced
}
}
}
I want to test if I see correct state
emissions if I call sync()
stojan
12/02/2021, 2:28 PMursus
12/02/2021, 2:29 PMtest,
In runBlocking?mkrussel
12/02/2021, 2:38 PMSyncer
for testing. Then you could inject unconfined to make the launch happen immediately.ursus
12/02/2021, 3:06 PMmkrussel
12/02/2021, 3:09 PMstate
variable was returning the current value of the flow, but it is returning the actual flow, so you can use turbine to test it.
Should probably change the return type to be Flow
instead of MutableFlow
or else there is no point in having the two properties.ursus
12/02/2021, 3:11 PMmkrussel
12/02/2021, 3:13 PMursus
12/02/2021, 3:14 PMmkrussel
12/02/2021, 3:15 PMursus
12/02/2021, 3:16 PMmkrussel
12/02/2021, 3:24 PMTestDispatcher
Syncer
anymore and there are no jobs running.ursus
12/02/2021, 3:28 PMmkrussel
12/02/2021, 3:31 PMrunBlocking
scope might make more sense though. It would then be the same thread as the test, which is likely more similar to how the view model works with MainScope.ursus
12/02/2021, 3:36 PMstojan
12/02/2021, 3:50 PMursus
12/02/2021, 4:08 PMstojan
12/02/2021, 4:13 PMDefault
for whatever is done in VM, network layer uses IO
, I switch to Main
in the Fragment
stojan
12/02/2021, 4:14 PMIO
) but doesn't matter that muchursus
12/02/2021, 4:19 PMviewModel.viewState.test {
awaitItem() shouldBe Loading
awaitItem() shouldBe problem
}
should this not wait infinitely, since viewState is noncompleting?stojan
12/02/2021, 4:26 PMcollect
(which would suspend infinitely)ursus
12/02/2021, 4:36 PMcancelAndIgnoreRemainingEvents
other wise it should suspend there forever, no?stojan
12/02/2021, 4:39 PM