Last active
December 11, 2015 23:48
-
-
Save benjchristensen/4679253 to your computer and use it in GitHub Desktop.
Example of using RxJava in Groovy to compose nested asynchronous calls.
This file contains hidden or 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
/** | |
* Demonstrate how Rx is used to compose Observables together | |
* such as how a web service would to generate a JSON response. | |
* | |
* The simulated methods for the metadata represent different | |
* services that are often backed by network calls. | |
* | |
* This will return a sequence of dictionaries such as this: | |
* | |
* [id:1000, title:video-1000-title, length:5428, bookmark:0, | |
* rating:[actual:4, average:3, predicted:0]] | |
*/ | |
def Observable getVideoGridForDisplay(userId) { | |
getListOfLists(userId).mapMany({ VideoList list -> | |
// for each VideoList we want to fetch the videos | |
list.getVideos() | |
.take(10) // we only want the first 10 of each list | |
.mapMany({ Video video -> | |
// for each video we want to fetch metadata | |
def m = video.getMetadata().map({ | |
Map<String, String> md -> | |
// transform to the data and format we want | |
return [title: md.get("title"), | |
length: md.get("duration")] | |
}) | |
def b = video.getBookmark(userId).map({ | |
position -> | |
return [bookmark: position] | |
}) | |
def r = video.getRating(userId).map({ | |
VideoRating rating -> | |
return [rating: | |
[actual: rating.getActualStarRating(), | |
average: rating.getAverageStarRating(), | |
predicted: rating.getPredictedStarRating()]] | |
}) | |
// compose these together | |
return Observable.zip(m, b, r, { | |
metadata, bookmark, rating -> | |
// now transform to complete dictionary of data | |
// we want for each Video | |
return [id: video.videoId] << metadata << bookmark << rating | |
}) | |
}) | |
}) | |
} | |
// emits results such as | |
[id:1002, title:video-1002-title, length:5428, bookmark:0, | |
rating:[actual:2, average:4, predicted:3]] | |
[id:1003, title:video-1003-title, length:5428, bookmark:0, | |
rating:[actual:4, average:4, predicted:4]] | |
[id:1004, title:video-1004-title, length:5428, bookmark:0, | |
rating:[actual:4, average:1, predicted:1]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The full example is at https://gist.github.com/4679246