Thomas Flad
12/09/2021, 12:42 PMshareIn
operator + WhileSubscribed
to cancel/resume the SharedFlow in repeatOnLifecycle
when the Android App goes to background. It’s working fine so far. I also combine this flow with a MutableStateFlow in my ViewModel to react on user input and update my state.
class MyViewModel(
dataSource: MyDataSource,
sharingStarted: SharingStarted = WhileSubscribed(5000)
) : ViewModel() {
var userInput = MutableStateFlow(1)
val state = dataSource.dataFlow()
.combine(userInput) { data, userInput ->
OutputClass(data, userInput)
}
.shareIn(viewModelScope, sharingStarted, 1)
}
My issue is that I want to test this. I’ve tried to use Turbine for this but it does not help with the combine.
@Test
fun testMyViewModel() = runBlockingTest {
val cut = MyViewModel(
mockk { coEvery { dataFlow() } returns flowOf(Data()) },
sharingStarted = SharingStarted.Eagerly
)
cut.state.test {
// Also an emit to the userInput here does not help
// cut.userInput.emit(2)
assertEquals(OutputClass(...), awaitItem())
}
}
I’m getting a timeout instead of the result.Tgo1014
12/09/2021, 12:48 PMrunBlockingTest
ursus
12/09/2021, 12:54 PMThomas Flad
12/09/2021, 12:55 PMursus
12/09/2021, 12:57 PMThomas Flad
12/09/2021, 3:02 PMrunBlocking
didn’t help.
What solves the issue kind of is when I pass a scope to the ViewModel and use the TestCoroutineScope for the shareIn
instead.
But then I’ll get Test finished with active jobs
ursus
12/09/2021, 3:07 PMshareIn
sharing, does it work?Thomas Flad
12/09/2021, 3:16 PMshareIn
without the combineexpensivebelly
12/09/2021, 4:56 PMcombine
or shareIn
but not both?Nick Allen
12/09/2021, 5:57 PMcancelAndConsumeRemainingEvents()
at end of test
block. test
doesn't return until Flow
is complete or cancelled. The result of shareIn
never completes so you need to cancel it. https://github.com/cashapp/turbine#hot-flows