简体   繁体   中英

How can I use data from another flow data in flow? (Kotlin Flow)

I wrote the code as below.

suspend fun getDataByRegion(): Flow<Result?> {
    // getRegion() return Flow<Region>
    return getRegion().map { region: Region ->
        repository.requestDataFromServer(region)
    }
}

The problem is that repository.requestDataFromServer(region) called twice.

So I think I should use operators like zip or combine .

When using these operators, how can the second flow use the data of the first flow?

With combine and zip operators you can not depend on the other's result. So in general your chaining approach with map is OK.

There is several options you have:

  • Assuming your repository method is not called from anywhere else, the reason for it being called twice is that the region Flow is emitting twice. So try to find out why this is the case.

    Anyhow if your region Flow method returns the same region twice you can fix it by simply adding .distinctUntilChanged() after getRegion() like:

     getRegion().distinctUntilChanged().map { region: Region -> repository.requestDataFromServer(region) }

    It will make sure your region Flow doesn't emit redundantly with the same data. Alternatively add distinctUntilChanged() directly to the repository method, if this is always the expected behavior.

  • Ask yourself if this method really needs to return a stream ( Flow ). I guess you need a stream since the region can change at runtime and you want something in your app to update automatically? But if not you could simply convert the stream to a single result:

     val region = getRegion().first() repository.requestDataFromServer(region)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM