Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Observable<List<Car>> to a sequence of Observable<Car> in RxJava

Given a list of cars (List<Car> cars), I can do:

Observable.just(cars); //returns an Observable that emits one List<Car> Observable.from(cars); //returns an Observable that emits a squence of Car 

Is there a way I can go from an Observable of a List<Car> to a sequence of Observable<Car>?

Something like a from without parameters

Obserable.just(cars).from() 
like image 718
Giorgio Avatar asked Apr 16 '15 11:04

Giorgio


People also ask

How do I convert Observable to maybe?

Unfortunately, there is no straightforward way to convert an Observable to Maybe (unless you are interested in just the firstElement ). You can convert it to Single first though and then to Maybe using toMaybe . This observable is only concerned about two things, if some action is executed or an error is encountered.

How do I extract an object from Observable?

You cannot 'extract' something from an observable. You get items from observable when you subscribe to them (if they emit any). Since the object you are returning is of type Observable, you can apply operators to transform your data to your linking.


Video Answer


2 Answers

You can map an Observable<List<Car>> to Observable<Car> like so:

yourListObservable.flatMapIterable(x -> x) 

Note that flatMapping might not preserve the order of the source observable. If the order matters to you, use concatMapIterable. Read here for more details.

like image 98
Egor Neliuba Avatar answered Sep 22 '22 14:09

Egor Neliuba


you can use this

flatMap { t -> Observable.fromIterable(t) } 
like image 24
Mohammad Sultan Al Nahiyan Avatar answered Sep 25 '22 14:09

Mohammad Sultan Al Nahiyan