Home » Android » Create Observable that emits asynchronously

Create Observable that emits asynchronously

Posted by: admin November 1, 2017 Leave a comment


I want to create an Observable that detects things. These are discovered in time and aren’t available when the Subscriber subscribes. How do I approach this?

My attempt was to create an Observable as so:

Observable.create(new AsyncOnSubscribe<Object, Thing>() {
    protected Object generateState() { return null; /* state not presented for the sake of simplicity */ }

    protected Object next(Object state, long requested, Observer<Observable<? extends Thing>> observer) {
        if(haveMoreThings()) {
            while (!nextThingAvailable()) {

        } else {
        return null;

This works but is a no-go since there are some issues I cannot figure out:

First problem
How do I check that the observer hasn’t unsubscribed? Using the deprecated Observable.create() one could do:

Observable.create(subscriber -> {
                // stop detecting things

Second problem: Whats the proper way to wait until something is available (within the observable)? Is SystemClock.sleep(x); the way to go?

Design question: It might be easier to just use a Subject for this but I don’t have enough exp with rxJava to justify this opinion. In case this is the way to go it’ll be awesome if an example was provided.


It still isn’t clear what you are trying to do. You likely do not need to create an observable, but use Subject instead.

PublishSubject<Thing> thingDetector = PublishSubject.create();

// detector loop
while ( true ) {
  Thread.sleep( 100 );
  if ( haveAnItem ) {
    thingDetector.onNext( next() );
  if ( allItemsDone ) {

Since you don’t specify how you interface with the thing, I can’t be more specific.