A practical guide to using RxJava on Android. Tips for improving your app architecture with reactive programming. What are the advantages and disadvantages of using RxJava over standard architecture? And how to connect with other popular Android libraries?
Presented at Droidcon Greece 2016.
14. Key parts
• Observable
• Observer or Subscriber
• onNext(T)
• onCompleted()
• onError(Throwable)
• Subject
15. What is RxJava good for?
• making code simple and readable
• Async processing
• no AsyncTask, AsyncTaskLoader, …
• Async composition
• RxJava offers simple chaining of async operations
• eliminates callback hell
58. RxLifecycle
• auto unsubscribe based on Activity/Fragment
lifecycle
myObservable
.compose(
RxLifecycle.bindUntilEvent(
lifecycleObservable, ActivityEvent.DESTROY
)
)
.subscribe(…);
myObservable
.compose(RxLifecycle.bindActivity(lifecycleObs))
.subscribe(…);
59. RxLifecycle
• How to obtain ActivityEvent or
FragmentEvent?
A. rxlifecycle-components + subclass
RxActivity, RxFragment
B. Navi + rxlifecycle-navi
C. Write it yourself
60. RxLifecycle
public class MyActivity extends RxActivity {
@Override
public void onResume() {
super.onResume();
myObservable
.compose(bindToLifecycle())
.subscribe();
}
}
61. RxLifecycle & Navi
public class MyActivity extends NaviActivity {
private final ActivityLifecycleProvider provider
= NaviLifecycle.createActivityLifecycleProvider(this);
}
62. RxLifecycle & Navi
public class MyActivity extends NaviActivity {
private final ActivityLifecycleProvider provider
= NaviLifecycle.createActivityLifecycleProvider(this);
@Override
public void onResume() {
super.onResume();
myObservable
.compose(provider.bindToLifecycle())
.subscribe(…);
}
}
74. Retrofit
• sync or async API (Retrofit 2)
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId);
@GET("group/{id}/users")
Observable<List<User>> groupList(@Path("id") int groupId);
• reactive API
75. Retrofit
• onNext() with Response, then onComplete()
• onError() in case of error
@GET("/data")
Observable<Response> getData(
@Body DataRequest dataRequest);
82. SQLBrite
SqlBrite sqlBrite = SqlBrite.create();
BriteDatabase db = sqlBrite
.wrapDatabaseHelper(openHelper, Schedulers.io());
Observable<Query> users = db
.createQuery("users", "SELECT * FROM users");
83. SQLBrite
• subscribed queries updated when insert/update/delete
occurs
• necessary to run it through the same BriteDatabase
object
• can cause backpressure
• fix by using transactions = one update
• or use debounce()