Home > Mobile >  Why do we need to use collect/collectLatest in different launch blocks?
Why do we need to use collect/collectLatest in different launch blocks?

Time:08-19

lifeCycleScope.launch {
    viewModel.oneItem.collect {
        println("one")
    }

    viewModel.twoItem.collectLatest {
        println("two")
    }
}

I tried this code, but it only print 'one' and it seems like second collectLatest doesn't work. Why is that?

CodePudding user response:

The first collect function is a suspend function, it suspends current coroutine until all items are collected. If viewModel.oneItem is infinite then it will never go to the executing of viewModel.twoItem.collectLatest function. To invoke both functions in this case two coroutines must be launched:

lifeCycleScope.launch {
    launch {
        viewModel.oneItem.collect {
            println("one")
        }
    }
    
    launch {
        viewModel.twoItem.collectLatest {
            println("two")
        }
    }
}
  • Related