Skip to content

Instantly share code, notes, and snippets.

@benjchristensen
Created January 30, 2013 18:39
Show Gist options
  • Save benjchristensen/4675568 to your computer and use it in GitHub Desktop.
Save benjchristensen/4675568 to your computer and use it in GitHub Desktop.
Observable Method that optionally uses a thread to fetch data if not available in memory. Either way the response type is an Observable callback that can be composed using Rx operators.
/**
* Non-blocking method that immediately returns the value
* if available or uses a thread to fetch the value and
* callback via `onNext()` when done.
*/
def Observable<T> getData(int id) {
if(availableInMemory) {
// if data available return immediately with data
return Observable.create({ observer ->
observer.onNext(valueFromMemory);
observer.onCompleted();
})
} else {
// else spawn thread or async IO to fetch data
return Observable.create({ observer ->
executor.submit({
try {
// do work on separate thread
T value = getValueFromRemoteService(id);
// callback with value
observer.onNext(value);
observer.onCompleted();
}catch(Exception e) {
observer.onError(e);
}
})
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment