RxAndroid - run two observable in parallel and combine the result

1,610 views
Skip to first unread message

Mouna Cheikhna

unread,
Nov 4, 2014, 12:04:38 PM11/4/14
to rxj...@googlegroups.com
I have a service where i can ask for an image and some metadata separately : 
 with two observables : Observable<Metadata> and Observable<Image> 
I would like to run both in parallel and combine them so i can use observeOn(AndroidSchedulers.mainThread()); and use their results and display the image with its data.
I've tried multiple operators but most of them require observables of the same type, any pointers on how to do this ? 

Thanks.

Samuel Tardieu

unread,
Nov 4, 2014, 12:46:08 PM11/4/14
to Mouna Cheikhna, rxj...@googlegroups.com
Did you by chance miss the zip() family of operators?

  Sam

Matteo Landi

unread,
Nov 4, 2014, 1:42:25 PM11/4/14
to Samuel Tardieu, Mouna Cheikhna, rxj...@googlegroups.com
You could go with Observable.combineLatest() and for example make the aggregator function a tuple of metadata and image. --Matteo

Mouna Cheikhna

unread,
Nov 5, 2014, 3:13:45 AM11/5/14
to rxj...@googlegroups.com, s...@rfc1149.net, cheikh...@gmail.com
combineLatest seemed to be a viable solution only problem is that it may associate a bitmap with another metadata if a loading of a bitmap from Observable<Bitmap> happens before it's predecessor, 
is there a way to restrict combination on a common key or something like that ? 

Thanks

Shixiong Zhu

unread,
Nov 5, 2014, 6:55:00 AM11/5/14
to Mouna Cheikhna, rxj...@googlegroups.com, s...@rfc1149.net
Why not try `zip`?

Best Regards,

Shixiong Zhu

Arild Jacobsen

unread,
Nov 5, 2014, 7:10:40 AM11/5/14
to rxj...@googlegroups.com, cheikh...@gmail.com, s...@rfc1149.net
Sorry to be hammering this point, but I was mid-post when Shixiong Zhu posted. As both Shu and Samuel mentioned, zip definitely seems to be the correct operator for combining two observables in matched pairs. 
e.g.
    Observable.zip(imageObservable, metaDataObservable, new Func2<Image, Metadata, TupleOrSomething>() {
        @Override
        public TupleOrSomething call(Image img, Metadata meta) {
                return new TupleOrSomething(img, meta);
            }
        }).subscribe(new Subscriber<TupleOrSomething>() {...});

Mouna Cheikhna

unread,
Nov 5, 2014, 8:14:33 AM11/5/14
to rxj...@googlegroups.com, cheikh...@gmail.com, s...@rfc1149.net
I ended up using zip and it worked out pretty well. Thanks everyone
Reply all
Reply to author
Forward
0 new messages