Skip to content

Instantly share code, notes, and snippets.

@martinandersson
Last active September 5, 2018 10:19
Show Gist options
  • Save martinandersson/9453c02160eaac5ef30df3ff2e74816e to your computer and use it in GitHub Desktop.
Save martinandersson/9453c02160eaac5ef30df3ff2e74816e to your computer and use it in GitHub Desktop.
RxJava and what gets disposed
package com.hello;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.observables.ConnectableObservable;
/**
* Lesson learned: It is not the Observable that is disposed, it is the Observer
* that may get disposed. Rx's API and documentation continuously describe
* the Observable as the one being disposed, but this is wrong.
*/
public class Launcher
{
public static void main(String[] args) {
example1();
example2();
}
private static void example1() {
ConnectableObservable<String> hello = Observable.just("Hello, World!")
.publish();
Disposable obs1 = hello.subscribe(e -> System.out.println("Obs 1: " + e)),
obs2 = hello.subscribe(e -> System.out.println("Obs 2: " + e));
obs1.dispose();
// "Obs 2: Hello, World!"
hello.connect();
// I.e., obs1 was disposed, but not the Observable and obs2 continuous
// to operate.
}
private static void example2() {
Observable<String> obs = Observable.create(emitter -> {
System.out.println("New subscription lol.");
// JavaDoc says it is "the sequence" that got disposed, again
// indicating the Observable.
if (emitter.isDisposed()) {
System.out.println("Dude, someone disposed the observer lololol");
}
else {
emitter.onNext("wassup??");
emitter.onComplete();
}
});
// Prints..
// "New subscription lol."
// "Dude, someone disposed the stream/subscription lololol"
obs.subscribe(
/* onNext */ x -> {},
/* onError */ x -> {},
/* onComplete */ () -> {},
// onSubscribe; immediately dispose!
Disposable::dispose);
// Prints...
// "New subscription lol."
// "wassup??"
obs.subscribe(System.out::println);
// .. i.e., the Observable/emitter/sequence/whatever was not disposed!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment