Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert observable to list

I am using RxJava.

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

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

like image 497
Khanh Nguyen Avatar asked Oct 11 '14 05:10

Khanh Nguyen


4 Answers

Hope this helps.

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

thanks

anand raman

like image 76
diduknow Avatar answered Nov 09 '22 11:11

diduknow


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

observable.toList(myObservable)
          .subscribe({ myListOfSomething -> do something useful with the list });
like image 45
sol4me Avatar answered Nov 09 '22 09:11

sol4me


RxJava 2+:

List<T> = theObservarale
             .toList()
             .blockingGet();
like image 13
Andrew Avatar answered Nov 09 '22 10:11

Andrew


You can also use the collect operator:

    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.

like image 5
araknoid Avatar answered Nov 09 '22 09:11

araknoid