Skip to content

Instantly share code, notes, and snippets.

@andersio
Last active February 19, 2017 12:59
Show Gist options
  • Select an option

  • Save andersio/b306cc57b0f366f330a5a5c620380167 to your computer and use it in GitHub Desktop.

Select an option

Save andersio/b306cc57b0f366f330a5a5c620380167 to your computer and use it in GitHub Desktop.
// Assuming we have this state:
courseId
// Assuming we have these view related stuff:
refreshButton
courseCodeLabel
courseTitleLabel
sectionsAdapter // ArrayAdapter
sectionSpinner
// Fetch the course info when the observable is first subscribed,
// and subsequently when refreshes are requested.
//
// The result is cached, so that subscriptions share the latest
// fetched results and would not unnecessarily trigger network requests.
//
// P.S. `RxView.clicks` is from RxBinding.
Observable<Course> course = RxView.clicks(refreshButton)
.startWith(null)
// `fetchCourse` is a `(CourseId) => Course` function.
.concatMap(new Func1<Void, Course>() {
@Override public void call(Void a) {
return fetchCourse(courseId);
}
})
// We care about only the latest fetched result.
.cache(1)
// Basic bindings: Course code and course title
course.subscribe(new Action1<Course>() {
@Override public void call(Course course) {
courseCodeLabel.setText(course.code);
courseTitleLabel.setText(course.title);
}
})
// Advanced bindings: Filtered collection
// Let's assume there is one selection at a time only, since
// this is what Spinner supports.
//
// P.S. `RxAdapterView` is from RxBinding.
RxAdapterView.itemSelections(sectionSpinner)
// Assume `0` means "all".
.startWith(0)
// For every value we get from the upstream, pair it with
// the latest `Course` instance cached by `course`.
.withLatestFrom(course)
.map(new Func2<Int, Course, List<Section>>() {
@Override public void call(Int selection, Course course) {
return Course.filterSection(course, selection);
}
})
.subscribe(new Action1<List<Section>>() {
@Override public void call(List<Section> sections) {
sectionsAdapter.clear();
sectionsAdapter.addAll(sections);
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment