Home » Android » Create Observable that emits asynchronously

Create Observable that emits asynchronously

Posted by: admin November 1, 2017 Leave a comment

Questions:

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>() {
    @Override
    protected Object generateState() { return null; /* state not presented for the sake of simplicity */ }

    @Override
    protected Object next(Object state, long requested, Observer<Observable<? extends Thing>> observer) {
        if(haveMoreThings()) {
            while (!nextThingAvailable()) {
                SystemClock.sleep(100);
            }

            observer.onNext(Observable.just(getNextThing());
        } else {
            observer.onCompleted();
        }
        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 -> {
            if(subscriber.isUnsubscribed()){
                // 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.

Answers:

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 ) {
    thingDetector.onComplete();
  }
}

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