Skip to content
This repository was archived by the owner on Aug 16, 2023. It is now read-only.
This repository was archived by the owner on Aug 16, 2023. It is now read-only.

Something that is misleading in codelab: Learn advanced coroutines with Kotlin Flow and LiveData  #179

Open
@tangkegaga

Description

@tangkegaga

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 and getPlantsWithGrowZoneFlow 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 of flatMapLatest
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)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions