Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to zip 2 observables with different length in RxJava

I have two observables:

Observable<String[]>

and

Observable<KalturaVideo>

I want to check for every KalturaVideo.getId(), is it contains in String[], which returns first observable, and if it contains, then don't emmit it in sourceList.

So, first observable emmits String[] only one time, but second observable emmits items 17 times. How to compose this two observables properly? Here is my Solution:

private Observable<KalturaVideo> getSourceListObservalbe(String kalturaPlaylistId){
        Observable<String[]> targetIdList = Observable.just(targetList)
                .map((List<KalturaVideo> kalturaVideos) -> {
                    if(kalturaVideos == null || kalturaVideos.isEmpty()){
                        return new String[]{""};
                    }
                    String[] result = new String[kalturaVideos.size()];
                    int index = 0;
                    for (KalturaVideo item : kalturaVideos) {
                        result[index] = item.getId();
                    }
                    return result;
                });
        return Observable.zip(
                targetIdList,
                KalturaVideoRetriver.getVideoList(BuildPlaylistStep2Activity.this, kalturaPlaylistId),
                (String[] idListOfTarget, KalturaVideo kalturaVideo) -> {
                    for (String item :idListOfTarget){
                        if(item.equals(kalturaVideo.getId())){
                            return null;
                        }
                    }
                    return kalturaVideo;
                })
                .filter(kalturaVideo -> {
                    return kalturaVideo != null;
                });
    }

targetList - list of KalturaVideo, which I want to exclude from sourceList, KalturaVideoRetriver.getVideoList - returns sourceList

This solution gets me only one KalturaVideo, but I need 17

like image 320
Aleksandr Avatar asked Apr 19 '15 19:04

Aleksandr


1 Answers

You could use combineLatest rather than zip:

return Observable.combineLatest(
    targetIdList,
    KalturaVideoRetriver.getVideoList(BuildPlaylistStep2Activity.this, kalturaPlaylistId),
    (String[] idListOfTarget, KalturaVideo kalturaVideo) -> {
        ...
        return kalturaVideo;
    })

combineLatest works like zip, but it combines the most-recent emission of each.

So in your case, your targetIdList observable emits a single String[]. combineLatest will zip that with every emission from your other observable.

like image 159
Adam S Avatar answered Nov 19 '22 16:11

Adam S