Public Void @f2prateek

Cleaning up subscriptions

When you create a new Observable, you’ll often want to clean up whenever a Subscriber unsubscribes from the Observable. The Subscriber class exposes a handy add method that does exactly what we want.

For instance, here’s how you would create an Observable that emits the keys that were changed for some SharedPreferences. It registers a new OnSharedPreferenceChangeListener when a subscriber subscribes, and automatically unregisters the listener when the subscriber unsubscribes.

Observable.create((subscriber) -> {
        final OnSharedPreferenceChangeListener listener =
            (preferences, key) -> {
              subscriber.onNext(key);
            };

        preferences.registerOnSharedPreferenceChangeListener(listener);

        subscriber.add(Subscriptions.create(() -> {
            preferences.unregisterOnSharedPreferenceChangeListener(listener);
        }));
    });

On the Observer side of things, you can also enqueue actions to be executed each time a Subscriber unsubscribes from an Observable with the doOnUnSubscribe method.