Hi guys, I have two suspend methods that I launch...
# android
s
Hi guys, I have two suspend methods that I launch concurrently inside a ViewModel:
Copy code
init {
    viewModelScope.launch {
        launch { loadTotalCirculation() }
        launch { loadMarketPrice() }
    }
}

private suspend fun loadTotalCirculation() {
    val totalCirculation = bitcoinChartsRepository.getTotalCirculation(5, TimeUnit.HOURS)
    _viewState.value = _viewState.value.copy(totalCirculation = chartViewEntityMapper(totalCirculation))
}

private suspend fun loadMarketPrice() {
    val marketPrice = bitcoinChartsRepository.getMarketPrice(27, TimeUnit.DAYS)
    _viewState.value = _viewState.value.copy(marketPrice = chartViewEntityMapper(marketPrice))
}
However, I would like to prevent the concurrent execution of the
_viewState.value = _viewState.value.copy...
parts in both my methods. What's the best way to achieve this ? These two requests update parts of a stateflow that's collected inside a Fragment. However, often they run concurrently emitting the wrong states. Is there a way to better architect this solution ?
j
You could have the two suspend functions return their values instead of assigning internally. Then your init would be more like
Copy code
_viewState.value = _viewState.value.copy(
totalCirculation = loadTotalCirculation().await(), 
marketPrice = loadMarketPrice().await())
Another option, if you need each to update the UI on their own, would be to do a redux style where they post their results to a channel and you update your _viewState each time the channel emits.
s
Hi Jeff! That sure would work. I would prefer not to wait for both of those api calls to return before posting a view state to the ui. The channel approach seems like the way to go about it.
(Because of the await calls, the _viewState value will only be set after both the await calls have succeeded, right ?)
j
correct. you’d need a stream / channel to marshal the two updates w/o getting into mutable state issues.
👍 1