Karol Kulbaka
Karol Kulbaka

Reputation: 1274

MutableStateFlow collector doesn't receive data

I have some view model:

    private val locationFlow = locationProviderClient.locationFlow(LocationModule.locationRequest)

    val position = MutableStateFlow(Location(LocationManager.NETWORK_PROVIDER))
    val positions = MutableStateFlow(emptyList<Position>())

    init {
        collectLocation()
    }

    private fun collectLocation() {
        viewModelScope.launch {
            locationFlow.collect {
                position.value = it
                positions.value = positionService.updateLocation(it.toPosition())
            }
        }
    }

On initialization flow of current location is starting. On each new value last position should be emitted into position state flow and network request should be performed. Here's fragment code responsible for collecting state flows

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycleScope.launchWhenStarted {
                ...
                viewModel.positions.collect(updateMarkers)
                viewModel.position.collect(updateCamera)
                ...
            }
}

Now, when fragment starts location is emitted, both flows are updated, request is send updateMarkers is called but updateCamera is not.

I suppose there is some subtle bug, if no can anybody tell me what the hell I'm doing wrong?

Upvotes: 0

Views: 910

Answers (2)

charlie.7
charlie.7

Reputation: 329

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycleScope.launchWhenStarted {
                ...
                launch {
                   viewModel.positions.collect(updateMarkers)
                }
                launch {
                   viewModel.position.collect(updateCamera)
                }
                ...
            }
    }

Upvotes: 0

Siri
Siri

Reputation: 941

The collects of your two flows are not concurrent, they are still executed sequentially.


override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycleScope.launch(Dispatchers.IO) {
                ...
                viewModel.positions.collect(updateMarkers)
                ...
            }

        lifecycleScope.launch(Dispatchers.IO) {
                ...
                viewModel.position.collect(updateCamera)
                ...
            }
    }

Upvotes: 2

Related Questions