codelab-kotlin-coroutines
codelab-kotlin-coroutines copied to clipboard
Flow's onCompletion not being called
Hi,
As the guideline in https://codelabs.developers.google.com/codelabs/advanced-kotlin-coroutines/index.html?index=..%2F..index#13 suggests, the codelab is finished:
growZoneChannel.asFlow()
.mapLatest { growZone ->
_spinner.value = true
if (growZone == NoGrowZone) {
plantRepository.tryUpdateRecentPlantsCache()
} else {
plantRepository.tryUpdateRecentPlantsForGrowZoneCache(growZone)
}
}
.onCompletion {
_spinner.value = false
}
.catch { throwable ->
_snackbar.value = throwable.message
}
.launchIn(viewModelScope)
Even if you do the latest challenge to refactor all this, we would end up in this case:
init {
// When creating a new ViewModel, clear the grow zone and perform any related udpates
clearGrowZoneNumber()
loadDataFor(growZoneChannel) { growZone ->
_spinner.value = true
if (growZone == NoGrowZone) {
plantRepository.tryUpdateRecentPlantsCache()
} else {
plantRepository.tryUpdateRecentPlantsForGrowZoneCache(growZone)
}
}
}
//where the loadDataFor is just:
private fun <T> loadDataFor(source: ConflatedBroadcastChannel<T>, block: suspend (T) -> Unit) {
source.asFlow()
.mapLatest {
block(it)
}
.onCompletion {
_spinner.value = false
}
.catch { throwable ->
_snackbar.value = throwable.message
}
.launchIn(viewModelScope)
}
However, the onCompletion
method is not being called, and causing the _spinner
value not to be updated at the end. I don't know what's wrong but I did try my solution and did try finished_code directory also.