【问题标题】:Kotlin Coroutine: get List of (T) from Flow<sealed class <list of <T>>>Kotlin 协程:从 Flow<sealed class <list of <T>>> 中获取 (T) 列表
【发布时间】:2022-01-09 14:59:00
【问题描述】:

我有以下函数返回 Flow > > ,

fun getItems() : Flow&lt;Resources&lt;List&lt;Item&gt;?&gt;&gt;

如何从这个函数中获取项目列表?

其中资源类为流:

 sealed class Resources<out T>(val data: T?) {
    class Success<T>(data: T) : Resources<T>(data)
    class Error(val throwable: Throwable) : Resources<Nothing>(null)
    object Loading : Resources<Nothing>(null)

    
    override fun toString(): String {
        return when (this) {
            is Success -> "Success: $data"
            is Error -> "Error: ${throwable.message}"
            is Loading -> "Loading"
        }
    }
}

【问题讨论】:

  • Resources 长什么样子?
  • @ArpitShukla,我更新了我的问题
  • 如果响应不是Success,你想要什么?
  • 我有一个绑定适配器,在加载或错误时显示
  • 但是您正试图从 Flow 中获取一个列表,如果响应不是 Success,您想要一个空值吗?

标签: android kotlin mapping kotlin-coroutines flow


【解决方案1】:

试试这个代码:

val items: List<Item>? = getItems().first { it is Resources.Success }.data

它将从流中选择第一个 Success 发射。
请注意,first 是一个 suspend 函数,因此您只能从协程中调用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    相关资源
    最近更新 更多