I\'m looking for a Subject (or something similar) that can:
I achieve the expected result creating a customized Observable that wraps a publish subject and handles emission cache if there's no subscribers attached. Check it out.
public class ExampleUnitTest {
@Test
public void testSample() throws Exception {
MyCustomObservable myCustomObservable = new MyCustomObservable();
myCustomObservable.emit("1");
myCustomObservable.emit("2");
myCustomObservable.emit("3");
Subscription subscription = myCustomObservable.subscribe(System.out::println);
myCustomObservable.emit("4");
myCustomObservable.emit("5");
subscription.unsubscribe();
myCustomObservable.emit("6");
myCustomObservable.emit("7");
myCustomObservable.emit("8");
myCustomObservable.subscribe(System.out::println);
}
}
class MyCustomObservable extends Observable {
private static PublishSubject publishSubject = PublishSubject.create();
private static List valuesCache = new ArrayList<>();
protected MyCustomObservable() {
super(subscriber -> {
Observable.from(valuesCache)
.doOnNext(subscriber::onNext)
.doOnCompleted(valuesCache::clear)
.subscribe();
publishSubject.subscribe(subscriber);
});
}
public void emit(String value) {
if (publishSubject.hasObservers()) {
publishSubject.onNext(value);
} else {
valuesCache.add(value);
}
}
}
Hope that it helps!
Best Regards.