kotlin - 确定流何时不返回数据

标签 kotlin kotlin-flow

Kotlin 流程说明如下:

A suspending function asynchronously returns a single value, but how can we return multiple asynchronously computed values? This is where Kotlin Flows come in.

但是,如果我的流程来源是这样的,当它完成但没有返回任何数据时,有没有办法从流程中确定这一点?例如,如果流的源调用后端 API 但 API 没有返回数据,有没有办法确定流何时完成并且没有数据?

最佳答案

有一个onEmpty如果流程完成但未发出任何项目,将调用操作的方法。

它也可以用来向流发出一个特殊的值来表明它是空的。例如,如果您有事件流,您可以发出 EmptyDataEvent

或者你可以在这个 onEmpty lambda 中做任何你想做的事。

高度相关的还有 onCompletion方法

关于kotlin - 确定流何时不返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69552575/

相关文章:

Kotlin @Deprecated ReplaceWith 将函数更改为变量赋值

android - 在 kotlin 中使用房间作为单例

Kotlin 类型删除 - 为什么仅泛型类型不同的函数可编译,而仅返回类型不同的函数则不可编译?

android - 与 Livedata 不同,使用 Flow in Room 查询在更新表条目时不会触发刷新,但在我删除或插入条目时有效

kotlin - 库模式中的Kotlin Flow

android - 图像不会变得不可见

android - 将数据从 Viewmodel 设置为 Activity android kotlin

kotlin - 组合 Flow 和非 Flow api 响应 Kotlin

android - Kotlin 流 : How can i get the cache data from subscription in flow when i have new subscriber?

Kotlin Flow onBackpressureDrop RxJava2 模拟