Zeyad Gasser
Zeyad Gasser

Reputation: 1546

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 ??

Upvotes: 6

Views: 1592

Answers (2)

sockeqwe
sockeqwe

Reputation: 15929

You can use the distinct operator.

Upvotes: 5

zsxwing
zsxwing

Reputation: 20826

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);

Upvotes: 3

Related Questions