Something that is misleading in codelab: Learn advanced coroutines with Kotlin Flow and LiveData #179
Description
In chapter 12, https://developer.android.com/codelabs/advanced-kotlin-coroutines#11
The title is Switching between two flows
There are two cases of switching,
- functionally switch between
plantsFlow
andgetPlantsWithGrowZoneFlow
for the particular example app
if (growZone == NoGrowZone) {
plantRepository.plantsFlow
} else {
plantRepository.getPlantsWithGrowZoneFlow(growZone)
}
- switch between a triggering flow of UI events
growZoneFlow
and an output flow to introduce a flow API offlatMapLatest
growZoneFlow.flatMapLatest{ another flow }
This pattern shows how to integrate events (grow zone changing) into a flow. It does exactly the same thing as the LiveData.switchMap version–switching between two data sources based on an event.
Inside the flatMapLatest, we switch based on the growZone. This code is pretty much the same as the LiveData.switchMap version, with the only difference being that it returns Flows instead of LiveDatas
Personally, it makes more sense to refer to the API of flatMapLatest
,in that case, these information consuses me:
Basically, this lets us switch between different flows based on the value of growZone.
Flow's flatMapLatest extensions allow you to switch between multiple flows.
PlantListViewModel.kt
if (growZone == NoGrowZone) {
plantRepository.plantsFlow
} else {
plantRepository.getPlantsWithGrowZoneFlow(growZone)
}