Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava Merge without duplicates

I am kinda new to RxJava and I am trying to implement search function that searches local db and the server. I would like it merge both results and eliminate the duplicates, any ideas ??

like image 725
Zeyad Gasser Avatar asked Apr 04 '16 23:04

Zeyad Gasser


2 Answers

You can use the distinct operator.

like image 154
sockeqwe Avatar answered Oct 07 '22 10:10

sockeqwe


You can merge the local and remote results and use toMap to eliminate the duplicates.

Moreover, if you have more requirements, you can use collect and HashSet(or HashMap) which give you more control:

    Observable<Integer> local = Observable.just(1, 2, 3, 4);
    Observable<Integer> remote = Observable.just(1, 3, 5, 7);
    local.mergeWith(remote)
            .collect(() -> new HashSet<Integer>(), (set, v) -> set.add(v))
            .flatMap(Observable::from)
            .subscribe(System.out::println);
like image 33
zsxwing Avatar answered Oct 07 '22 10:10

zsxwing