RxJava Operators: collect()

October 29, 2018

collect()

In case you need a custom collection operator, you can use collect().
Two arguments are needed: an initialValueSupplier which creates the empty collection you want to use and a collector which specifies how each emitted item should be added to the collection.
For example if you want to collect elements into a HashSet:

import io.reactivex.Observable;

import java.util.HashSet;

public class Main {

    public static void main(String[] args) {
        Observable<String> myObservable = Observable.just("a", "b", "c", "d");

        myObservable.collect(HashSet::new, HashSet::add)
                    .subscribe(System.out::println);
    }
}

As the example above shows, the collect() operator uses a mutable container.
Another example for collect could be that you want to do a certain business logic just before adding the emissions into your collection:

import io.reactivex.Observable;

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {
        Observable<String> myObservable = Observable.just("a", "b", "c", "d");

        myObservable.collect(ArrayList::new, (list, value) -> {
                                System.out.println(String.format("Inserting '%s' into ArrayList", value));
                                list.add(value);
                            })
                    .subscribe(System.out::println);
    }
}

 

András Döbröntey

About the Author

András Döbröntey

Leave a Comment:

Bitnami