Код: Выделить всё
private val _uiState: MutableStateFlow =
MutableStateFlow(createInitialState(savedStateHandle))
val uiState: StateFlow = _uiState
.onStart { onViewSubscribed() }
.stateIn(
scope = viewModelScope,
started = sharingStarted,
initialValue = _uiState.value
)
Код: Выделить всё
@Test
fun `Test that tries to capture each emittion separately`() = runTest {
viewModel.stateFlow.test {
val initial = awaitItem()
assertEquals(initial.isLoading, false)
viewModel.setStates()
val loading = awaitItem()
assertEquals(loading.isLoading, true)
val loaded = awaitItem()
assertEquals(loaded.isLoading, false)
val loadingAgain = awaitItem()
assertEquals(loadingAgain.isLoading, true)
val loadedAgain = awaitItem()
assertEquals(loadedAgain.isLoading, false)
val loadingAgain2 = awaitItem()
assertEquals(loadingAgain2.isLoading, true)
}
}
Код: Выделить всё
fun setStates() {
viewModelScope.launch {
updateStateFlow { copy(isLoading = true) }
updateStateFlow { copy(isLoading = false) }
updateStateFlow { copy(isLoading = true) }
updateStateFlow { copy(isLoading = false) }
updateStateFlow { copy(isLoading = true) }
}
}
Код: Выделить всё
@ExperimentalCoroutinesApi
class MainDispatcherExtension(
private val testDispatcher: TestDispatcher = UnconfinedTestDispatcher()
) : BeforeEachCallback, AfterEachCallback {
override fun beforeEach(context: ExtensionContext?) {
Dispatchers.setMain(testDispatcher)
}
override fun afterEach(context: ExtensionContext?) {
Dispatchers.resetMain()
}
}
Код: Выделить всё
fun setStates() {
viewModelScope.launch {
updateStateFlow { copy(isLoading = true) }
delay(1)
updateStateFlow { copy(isLoading = false) }
delay(1)
updateStateFlow { copy(isLoading = true) }
delay(1)
updateStateFlow { copy(isLoading = false) }
delay(1)
updateStateFlow { copy(isLoading = true) }
}
}
Я прочитал эту статью о «объединении» потока состояний и попытался применить ее решение, изменив свой диспетчер runTest на StandardTestDispatcher:
Код: Выделить всё
@ExperimentalCoroutinesApi
class MainDispatcherExtension(
private val testDispatcher: TestDispatcher = StandardTestDispatcher()
) : BeforeEachCallback, AfterEachCallback {
override fun beforeEach(context: ExtensionContext?) {
Dispatchers.setMain(testDispatcher)
}
override fun afterEach(context: ExtensionContext?) {
Dispatchers.resetMain()
}
}
Подробнее здесь: https://stackoverflow.com/questions/798 ... th-turbine
Мобильная версия