RxJava Operators: autoConnect()

November 16, 2018

autoConnect()

To make sure that a ConnectableObserverable automatically calls the connect() method after a given number of Observers subscribe, the autoConnect() operator can be used.

import io.reactivex.Observable;

import java.util.concurrent.ThreadLocalRandom;

public class Main {

    public static void main(String[] args)  {

        Observable<Integer> mySource = Observable.range(1, 3)
                                                 .map(x -> ThreadLocalRandom.current().nextInt(1, 100))
                                                 .publish()
                                                 .autoConnect(2);

        mySource.subscribe(x -> System.out.println(String.format("Observer 1: %d", x)));
        mySource.subscribe(x -> System.out.println(String.format("Observer 2: %d", x)));
    }
}

The downside of autoConnect() is that you have to know the number of Observers which will subscribe.
The default value for autoConnect() is 1: after the first subscription, the Observable will start emitting items.
If 0 is passed to autoConnect() as a parameter, it will start emitting the items immediately without waiting for any Observers.

András Döbröntey

About the Author

András Döbröntey

Leave a Comment:

Bitnami