Ahmed Ibrahim
07/05/2022, 12:18 PMrunCurrentStateFlow<MyStatecombine(flow1, flow2...Ahmed Ibrahim
07/05/2022, 12:18 PMinternal class MyViewModel : ViewModel() {
    private val isLoading = MutableStateFlow(false)
    private val isLoggedIn = MutableStateFlow(false)
    data class MyState(
        val isLoading: Boolean = false,
        val isLoggedIn: Boolean = false
    )
    val state: StateFlow<MyState> by lazy {
        combine(isLoading, isLoggedIn) { isLoading, isLoggedIn ->
            MyState(isLoading, isLoggedIn)
        }.stateIn(
            viewModelScope,
            SharingStarted.WhileSubscribed(),
            MyState(isLoading = false, isLoggedIn = false)
        ).also { init() }
    }
    private fun init() {
        viewModelScope.launch {
            isLoading.value = true
            isLoading.value = false
            isLoggedIn.value = true
        }
    }
}internal class CombineTest {
    @Test
    fun `combine should emit all intermediate values when new test api are used`() {
        Dispatchers.setMain(StandardTestDispatcher())
        runTest {
            val viewModel = MyViewModel()
            val emissions = mutableListOf<MyViewModel.MyState>()
            val job = launch {
                viewModel.state.toList(emissions)
            }
            runCurrent()
            assertEquals(
                listOf(
                    // Initial State
                    MyViewModel.MyState(isLoading = false, isLoggedIn = false),
                    // Loading is shown
                    MyViewModel.MyState(isLoading = true, isLoggedIn = false),
                    // Loading is hidden
                    MyViewModel.MyState(isLoading = false, isLoggedIn = false),
                    // We're now logged in
                    MyViewModel.MyState(isLoading = false, isLoggedIn = true)
                ),
                emissions
            )
            job.cancel()
        }
        Dispatchers.resetMain()
    }
}Joffrey
07/05/2022, 12:54 PMinit()valuerunCurrentAhmed Ibrahim
07/05/2022, 1:04 PMemitvalueemitvalueJoffrey
07/05/2022, 1:14 PMAhmed Ibrahim
07/05/2022, 1:40 PMcombine.value=Joffrey
07/05/2022, 1:45 PMcombinestateInThe value of mutable state flow can be updated by setting its value property. Updates to the value are always conflated. So a slow collector skips fast updates, but always collects the most recently emitted value."Slow" here is a relative term. In your case, your coroutine in
initAhmed Ibrahim
07/05/2022, 2:39 PMinitdelayvalue=advanceUntilIdleJoffrey
07/05/2022, 3:03 PMinitStateFlowinitvalueStateFlowrunCurrentAhmed Ibrahim
07/05/2022, 3:08 PMNick Allen
07/05/2022, 5:59 PMBut isn't this howNo.works? with every update to a flow that backs it, it emits a new state, based on that updated value, no?combine
combineFlowChannelChannelFlow