gpt4 book ai didi

android - 合并多个 Single 形成一个 Observable

转载 作者:太空狗 更新时间:2023-10-29 16:27:35 25 4
gpt4 key购买 nike

我正在编写一个 Android 应用程序,它需要按以下顺序执行 2 个查询:

  1. 向返回 Single<List<String>> urls 的库发出请求(我们称之为 RequestA) .
  2. 根据我从 RequestA 收到的信息,我必须使用这些 URL 中的每一个向另一个库发出请求 (RequestB)。每个 RequestB 现在都返回一个 Single。

现在我已经将所有 RequestB 中的所有 Single 组合起来形成一个可观察对象。

类似于 Observable.mergedelayerror(List<Single>) .我不能这样做,因为 mergedelayerror期待 iterableObservableSource .

我知道我可以通过实现回调和使用一些丑陋的逻辑来实现这一点,但我真的正在寻找一种仅使用 RX 提供的运算符的解决方案

最佳答案

这是一个解释的 kotlin 示例。 Java 版本几乎相同。您可能需要查看这些运算符的弹珠图,以便更容易直观地了解正在发生的事情。

getData() //<--- original api call that returns a list of urls                                                                                                                                                   
.flatMapObservable { list ->
//<- Since we are on a single we have to convert to an observable to emit each item onto the stream
Observable.fromIterable(list) // <-- create that observable that emits each item
}
.flatMapSingle { url ->
// we a single url entering here and have add it's result onto the stream but since it's a single we use flatMapSingle instead
secondApi(url) // we call our second api here
}
.toList() // <-- you may want to group them into a list
.subscribeOn(Schedulers.io()) // <-- causes the work to be done on the io scheduler so that you don't hit network on mainthread exception nor slow down the ui
.observeOn(AndroidSchedulers.mainThread()) // <-- causes the outcome to be on the ui thread so you can safely update without getting an illegal state exception can't update the ui from a now ui thread
.subscribe { next, error ->
next?.let {
//add to an adapter or something else
}
error?.let{
// handle error
}
}

关于android - 合并多个 Single 形成一个 Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46340246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com