'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?
Solution 1:[1]
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)
...
}
}
Solution 2:[2]
If you are updating UI it should be call from main thread
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleScope.launch(Dispatchers.IO) {
...
viewModel.positions.collect(updateMarkers)
viewModel.position.collect(updateCamera)
...
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Future Deep Gone |
| Solution 2 | charlie.7 |
