简体   繁体   English

RxJava。 将列表的可热观测数据转换为单项流,对其进行处理并转换回列表

[英]RxJava. Convert hot observable of list to single item stream, process it and convert to list back

Assuming i have a hot observable of lists of some items; 假设我有一些物品清单的热门观察;

Observable<List<Item>> observable = ...;

I need to convert it to single items stream and perform some operation on each item, like filtering, after that i should convert it back to list and process it in onNext method of subscriber: 我需要将其转换为单个项目流,并对每个项目执行一些操作,例如过滤,之后我应将其转换回列表并在订户的onNext方法中对其进行处理:

observable.flatMap(Observable::from)
    .filter(Item::isFiltered)
    .toList()
    .subscribe(this::onNext, this::onError)

public void onNext(List<Item> items) {...}

From the first look it seems ok, but it isn't, because our observable is hot , so toList() won't be ever executed (because it waits for source observable completion) and whole stream stucks. 乍一看似乎还可以,但是不是,因为我们的observable 很热 ,所以toList()永远不会执行(因为它等待源可观察的完成),并且整个流都卡住了。

How can i resolve this problem? 我该如何解决这个问题? Also please note that near the filter could be any amount of additional operations over single item. 另外请注意,在filter附近可能有多项针对单个项目的其他操作。

You can do all of your operations on single items and your final toList operator on the Observable you create in flatMap .. That way, you receive onComplete call and toList will collect and transform the items. 您可以对单个项目执行所有操作,并可以在flatMap创建的Observable上执行最终的toList运算符。这样,您将收到onComplete调用,并且toList将收集并转换项目。

observable.flatMap(list -> {
     return Observable.from(list)
                        .filter(Item::isFiltered)
                        .toList()
  })
  .subscribe(this::onNext, this::onError)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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