Created
January 30, 2013 18:39
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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