Skip to content

Instantly share code, notes, and snippets.

@oldergod
Last active January 19, 2018 22:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oldergod/ef39955861907dc322c4ba66fe1eb168 to your computer and use it in GitHub Desktop.
Save oldergod/ef39955861907dc322c4ba66fe1eb168 to your computer and use it in GitHub Desktop.
Managing RxState Starting point
/**
* Many things are omitted to focus on the relevant data.
*/
public class Activity extends AppCompatActivity {
Binder binder;
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
bind();
}
private void bind() {
binder.compose(intents()).subscribe(this::render);
}
public Observable<Intent> intents() {
return Observable.merge(loadFirstPageIntent(), loadNextPageIntent());
}
/** on creation */
public Observable<Intent.LoadFirstPageIntent> loadFirstPageIntent() {}
/** on bottom of list */
public Observable<Intent.LoadNextPageIntent> loadNextPageIntent() {}
public void render(ViewState state) {
// Update the UI
}
}
/**
* Many things are omitted to focus on the relevant data.
* See Jake's talk for the flow explanation: http://jakewharton.com/the-state-of-managing-state-with-rxjava/
*/
class Binder {
private Service service;
Binder(Service service) {
this.service = service;
}
Observable<ViewState> compose(Observable<Intent> intents) {
return intents
.map(this::actionFromIntent)
.compose(actionToResultTransformer)
.scan(ViewState.idle(), reducer);
}
// Emits loading, success and failure events.
private ObservableTransformer<Action.LoadFirstPageAction, Result.LoadFirstPageResult>
loadFirstPageTransformer;
// Emits loading, success and failure events.
private ObservableTransformer<Action.LoadNextPageAction, Result.LoadNextPageResult>
loadNextPageTransformer;
private ObservableTransformer<Action, Result> actionToResultTransformer =
actions -> actions.publish(shared -> Observable.merge(
shared.ofType(Action.LoadFirstPageAction.class).compose(loadFirstPageTransformer),
shared.ofType(Action.LoadNextPageAction.class).compose(loadNextPageTransformer));
private Action actionFromIntent(Intent intent) {
// Create an Action from an Intent.
}
private static BiFunction<ViewState, Result, ViewState> reducer =
(previousState, result) -> {
// Create new state from previousState
// Update the new state accordingly to the result
// Return it
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment