1

It seems to me that I do not quite understand something. Could you please explain to me why when I use this example, only the first collect works for me.

    lifecycleScope.launch {
        viewModel.test1.flowWithLifecycle(lifecycle, Lifecycle.State.STARTED).collect {
            Log.i("Log_tag", it)
        }
        viewModel.test2.flowWithLifecycle(lifecycle, Lifecycle.State.STARTED).collect {
            Log.i("Log_tag", it)
        }
    }

or if i call them like this:

  lifecycleScope.launch {
        viewLifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED){
            viewModel.test1.collect {
                Log.i("Log_tag", it)
            }
            viewModel.test2.collect {
                Log.i("Log_tag", it)
            }
        }
    }

But if I call them in different coroutines, then they work both, as here:

  lifecycleScope.launch {
        viewModel.test1.flowWithLifecycle(lifecycle, Lifecycle.State.STARTED).collect {
            Log.i("Log_tag", it)
        }

    }

    lifecycleScope.launch {
        viewModel.test2.flowWithLifecycle(lifecycle, Lifecycle.State.STARTED).collect {
            Log.i("Log_tag", it)
        }
    }

viewModel:

class ForecastViewModel : ViewModel() {
private val _test1 = MutableStateFlow("")
private val _test2 = MutableStateFlow("")
val test1 = _test1.asStateFlow()
val test2 = _test2.asStateFlow()

fun getTest() {
    viewModelScope.launch {
        _test1.value = "test1"
        _test2.value = "test2"

    }
}

1 Answers1

0

Collecting a StateFlow never finishes, because StateFlows don't terminate.

This is pretty much expected. Launching concurrent collectors is the right thing.

(I wonder if they could "override" StateFlow.collect to have return type Nothing to make that clearer.)

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413