Subjects are essentially are both Observables and Observers.
An Observable is essentially a thing that has a function that takes an Observer and returns a subscription. So, for example, given simple observable:
Observable<Integer> observable = Observable.create(new Observable.OnSubscribeFunc<Integer>() {
@Override
public Subscription onSubscribe(Observer<? super Integer> observer) {
observer.onNext(3);
observer.onNext(2);
observer.onNext(1);
observer.onCompleted();
return Subscriptions.empty();
}
});
And here we would subscribe to it, to print out a line for each integer:
Subscription sub = observable.subscribe(new Action1<Integer>() {
@Override
public void call(Integer integer) {
System.out.println(integer);
}
});
You would unsubscribe on the above by calling sub.unsubscribe()
.
Here is a PublishSubject that does roughly the same thing:
PublishSubject<Integer> publishSubject = PublishSubject.create();
Subscription subscription = publishSubject.subscribe(new Action1<Integer>() {
@Override
public void call(Integer integer) {
System.out.println(integer);
}
});
publishSubject.onNext(3);
publishSubject.onNext(2);
publishSubject.onNext(1);
You would unsubscribe from it the same way, by calling subscription.unsubscribe()
.