codelab-kotlin-coroutines icon indicating copy to clipboard operation
codelab-kotlin-coroutines copied to clipboard

Use collectLatest instead of mapLatest for reading GrowZone values

Open jbluntz opened this issue 5 years ago • 0 comments
trafficstars

In the final version of PlantListViewModel, mapLatest is used to trigger repository updates whenever the filter is toggled; this was hard for me to understand at first as I expected the result of the map function to be used somewhere, but it turns out it just triggers side effects. Would something like the following work?

viewModelScope.launch {
    growZoneChannel.asFlow().collectLatest { growZone ->
        _spinner.value = true
        try {
            if (growZone == NoGrowZone) {
                plantRepository.tryUpdateRecentPlantsCache()
            } else {
                plantRepository.tryUpdateRecentPlantsForGrowZoneCache(growZone)
            }
        } catch(t: Throwable) {
            _snackbar.value = t.message
        } finally {
            _spinner.value = false
        }
    }
}

I'm not incredibly familiar with coroutines/flow, but I think this still provides the benefits that the codelab mentions (canceling underlying network/storage operations if the viewModel is destroyed or if new GrowZone values are emitted). It would also bring the catch up into standard imperative style and make all the UI changes as part of the terminal operator.

jbluntz avatar Dec 04 '19 17:12 jbluntz