Skip to content

Instantly share code, notes, and snippets.

@anitaa1990
Last active August 17, 2018 13:46
Show Gist options
  • Save anitaa1990/247ec8e276b935bf8b574a37f99af81e to your computer and use it in GitHub Desktop.
Save anitaa1990/247ec8e276b935bf8b574a37f99af81e to your computer and use it in GitHub Desktop.
final List<String> alphabets = getAlphabetList();
/*
* Observable.create() -> We will need to call the
* respective methods of the emitter such as onNext()
* & onComplete() or onError()
*
* */
Observable observable = Observable.create(new ObservableOnSubscribe() {
@Override
public void subscribe(ObservableEmitter emitter) {
try {
/*
* The emitter can be used to emit each list item
* to the subscriber.
*
* */
for (String alphabet : alphabets) {
emitter.onNext(alphabet);
}
/*
* Once all the items in the list are emitted,
* we can call complete stating that no more items
* are to be emitted.
*
* */
emitter.onComplete();
} catch (Exception e) {
/*
* If an error occurs in the process,
* we can call error.
*
* */
emitter.onError(e);
}
}
});
/*
* We create an Observer that is subscribed to Observer.
* The only function of the Observer in this scenario is
* to print the valeus emitted by the Observer.
*
* */
Observer observer = new Observer() {
@Override
public void onSubscribe(Disposable d) {
System.out.println("onSubscribe");
}
@Override
public void onNext(Object o) {
System.out.println("onNext: " + o);
}
@Override
public void onError(Throwable e) {
System.out.println("onError: " + e.getMessage());
}
@Override
public void onComplete() {
System.out.println("onComplete");
}
};
/*
* We can call this method to subscribe
* the observer to the Observable.
* */
observable.subscribe(observer);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment