简体   繁体   English

将 observable 转换为列表

[英]Convert observable to list

I am using RxJava.我正在使用 RxJava。

I have an Observable<T> .我有一个Observable<T> How do I convert it to List<T> ?如何将其转换为List<T>

Seems to be a simple operation, but I couldn't find it anywhere on the net.似乎是一个简单的操作,但我在网上的任何地方都找不到。

Hope this helps.希望这可以帮助。

List<T> myList = myObservable.toList().toBlocking().single();

thanks谢谢

anand raman阿南德拉曼

You can use toList() or toSortedList() .您可以使用toList()toSortedList() For eg例如

observable.toList(myObservable)
          .subscribe({ myListOfSomething -> do something useful with the list });

RxJava 2+: RxJava 2+:

List<T> = theObservarale
             .toList()
             .blockingGet();

You can also use the collect operator:您还可以使用collect运算符:

    ArrayList list = observable.collect(ArrayList::new, ArrayList::add)
                               .toBlocking()
                               .single();

With collect , you can choose which type of Collection you prefer and perform an additional operation on the item before adding it to the list.使用collect ,您可以选择您喜欢的Collection类型,并在将项目添加到列表之前对其执行附加操作。

You can't convert observable to list in any idiomatic way, because a list isn't really a type that fits in with Rx.您不能以任何惯用的方式将 observable 转换为列表,因为列表并不是真正适合 Rx 的类型。

If you want to populate a list with the events from a observable stream you need to basically create a list and add the items within a Subscribe method like so (C#):如果要使用可观察流中的事件填充列表,您需要基本上创建一个列表并在Subscribe方法中添加项目,如下所示 (C#):

IObservable<EventType> myObservable = ...;
var list = new List<EventType>();
myObservable.Subscribe(evt => list.Add(evt));

The ToList -style operators only provide a list once the stream completes (as an IObservable<List<T>> ), so that isnt useful in scenarios where you have a long-lived stream or you want to see values before the stream completes. ToList样式运算符仅在流完成后提供列表(作为IObservable<List<T>> ),因此在您拥有长期流或您希望在流完成之前查看值的情况下,这没有用。

This works.这有效。

public static void main(String[] args) {

    Observable.just("this", "is", "how", "you", "do", "it")
            .lift(customToList())
            .subscribe(strings -> System.out.println(String.join(" ", strings)));

}

public static <T> ObservableOperator<List<T>, T> customToList() {

    return observer -> new DisposableObserver<T>() {

        ArrayList<T> arrayList = new ArrayList<>();
        @Override
        public void onNext(T t) {
            arrayList.add(t);
        }

        @Override
        public void onError(Throwable throwable) {
            observer.onError(throwable);
        }

        @Override
        public void onComplete() {
            observer.onNext(arrayList);
            observer.onComplete();
        }
    };
}`

This might be a late answer, hope it helps somebody in future.这可能是一个迟到的答案,希望它在未来对某人有所帮助。

There is an operator collectInto() .有一个运算符collectInto() I would suggest everyone to not use blocking() (unless in a test case) as you completely loose the purpose of async events in Rxchains .我建议大家不要使用Rxchains blocking() (除非在测试用例中),因为你完全失去了Rxchains中异步事件的目的。 Try to chain your operations as much as possible尝试尽可能多地链接您的操作

Completable setList(List<Integer> newIntegerList, Observable<Integer> observable){
   return observable.collectInto(newIntegerList, List::add).ignoreElement();
}

 // Can call this method
 Observable<Integer> observable = Observable.just(1, 2, 3);
 List<Integer> list = new ArrayList<>();
 setList(list, observable);

You save the hassle of using blocking() in this case.在这种情况下,您可以省去使用blocking()的麻烦。

Found it myself自己找的

public static <T> List<T> toList(Observable<T> observable) {
    final List<T> list = new ArrayList<T>();

    observable.toBlocking().forEach(new Action1<T>() {
        @Override
        public void call(T t) {
            list.add(t);
        }
    });

    return list;
}

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

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