Java 将 observable 转换为列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26311513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:12:12  来源:igfitidea点击:

Convert observable to list

javarx-javareactive-programming

提问by Khanh Nguyen

I am using RxJava.

我正在使用 RxJava。

I have an Observable<T>. How do I convert it to List<T>?

我有一个Observable<T>. 我如何将其转换为List<T>

Seems to be a simple operation, but I couldn't find it anywhere on the net.

似乎是一个简单的操作,但我在网上的任何地方都找不到。

采纳答案by sol4me

You can use toList()or toSortedList(). For e.g.

您可以使用toList()toSortedList()。例如

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

回答by Khanh Nguyen

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;
}

回答by diduknow

Hope this helps.

希望这可以帮助。

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

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

thanks

谢谢

anand raman

阿南德拉曼

回答by Andrey

RxJava 2+:

RxJava 2+:

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

回答by Hyman Ukleja

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 Subscribemethod 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>>),这样在你有一个长寿命的流或者你想流完成之前看到的场景值未启用有用。

回答by araknoid

You can also use the collectoperator:

您还可以使用collect运算符:

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

With collect, you can choose which type of Collectionyou prefer and perform an additional operation on the item before adding it to the list.

使用collect,您可以选择Collection您喜欢的类型并在将其添加到列表之前对该项目执行附加操作。

回答by Shubham Srivastava

This might be a late answer, hope it helps somebody in future.

这可能是一个迟到的答案,希望它在未来对某人有所帮助。

There is an operator 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. Try to chain your operations as much as possible

有一个运营商collectInto()。我建议每个人都不要使用blocking()(除非在测试用例中),因为您完全失去了Rxchains. 尝试尽可能多地链接您的操作

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()在这种情况下,您可以省去使用的麻烦。

回答by edmangini76

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();
        }
    };
}`