RxJava Operators: refCount(), share()

November 18, 2018

refCount() and share()

The refCount() operator behaves like an autoConnect(1) operator, but there is an important difference: when it has no Observers anymore, it will dispose itself and start over when a new Observer subscribes.

import io.reactivex.Observable;

import java.util.concurrent.TimeUnit;

public class Main {

    public static void main(String[] args) throws InterruptedException {

        Observable<Long> mySource = Observable.interval(1, TimeUnit.SECONDS)
                                              .publish()
                                              .refCount();

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

        Thread.sleep(2000);

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

        Thread.sleep(3000);

        //the Observable will start over here!
        mySource.take(2)
                .subscribe(x -> System.out.println(String.format("Observer 3: %d", x)));

        Thread.sleep(3000);
    }
}

The share() operator is a shorthand for Observable.publish().refCount():

import io.reactivex.Observable;

import java.util.concurrent.TimeUnit;

public class Main {

    public static void main(String[] args) throws InterruptedException {

        Observable<Long> mySource = Observable.interval(1, TimeUnit.SECONDS)
                                              .share();

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

        Thread.sleep(2000);

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

        Thread.sleep(3000);

        //the Observable will start over here!
        mySource.take(2)
                .subscribe(x -> System.out.println(String.format("Observer 3: %d", x)));

        Thread.sleep(3000);
    }
}
András Döbröntey

About the Author

András Döbröntey

Leave a Comment:

Bitnami