【问题标题】:Transform Single<List<Maybe<Book>>> to Single<List<Book>>将 Single<List<Maybe<Book>>> 转换为 Single<List<Book>>
【发布时间】:2021-03-20 20:28:12
【问题描述】:

有人可以帮忙吗?

我有这些功能

fun getBooks(): Single<List<Book>> {
    return getCollections()
        .map {
            it.map(::collectonToBook)
        }
}

fun getCollections(): Single<List<Collection>> {
   return db.fetchCollections()
       .filter(::isBook)
}

fun collectonToBook(collection: Collection): Maybe<Book> {
    return collection.toBook()
}
            

问题是当我需要 Single&lt;List&lt;Book&gt;&gt; 时 getBooks 返回 Single&lt;List&lt;Maybe&lt;Book&gt;&gt;&gt;。我可以在流中做到这一点而不调用blockingGet吗?

【问题讨论】:

    标签: kotlin rx-java2 rx-kotlin


    【解决方案1】:

    试试这个:

    getCollections()                        // Single<List<Collection>>
    .flattenAsFlowable { it }               // Flowable<Collection>
    .concatMapMaybe { collectonToBook(it) } // Flowable<Book>
    .toList()                               // Single<List<Book>>
    

    换句话说,将内部List 解包为其元素,将Collection 转换为Book,连接它们各自的Maybe 源,然后最后将Books 再次收集为List

    【讨论】:

    • 哇!它就像一个奇迹,非常感谢。并且为了快速响应!干杯!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    相关资源
    最近更新 更多