In the lifecycle scope with two StateFlow observers, only first works

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"

    }
}


from Recent Questions - Stack Overflow https://ift.tt/3vTF54A
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Spring Elasticsearch Operations

Network Error and Timeout on Authorize.net JS

Object oriented programming concepts (OOPs)