Share
Embed
A Practical Guide To understand Rx Streams
RxJava has helped us solve complex problems with ease and made our code manageable. In this talk we discuss how Capital One Wallet app uses RxJava 2, with practical examples. In our app, we follow Uncle Bob’s Clean Architecture with reactive approach. Our app has come a long way from using callbacks to RxJava 1 and eventually to RxJava 2. During this talk, we will discuss lots of tips and tricks that can help you prevent common mistakes.
This talk is suitable for intermediate users of Rx.
Mayank Mehta
August 26, 2017
Transcript
109 slides
-
Agenda • Terminology • Operators • Subject • Schedulers •
Reactive Source • Architecture • Appendix -
Architecture View state Repository Use case Presenter View Presentation Layer
Domain Layer Data Layer Observable<T> Observable<T> Observable<T> -
MVVM + RxJava • Modular • Testable • Concurrency is
easy • Better code • Happy developers -
Sources in RxJava • Observable<T> • Flowable<T> • Single<T> •
Maybe<T> • Completable<T> -
Observable • Emits 0 – n items • Terminates with
complete or error 1 3 2 4 -
Observable subscribe with observer public interface Observer<T> { void onSubscribe(Disposable
d); void onNext(T t); void onError(Throwable e); void onComplete() } -
Observable subscribe with observer public interface Observer<T> { void onSubscribe(Disposable
d); void onNext(T t); void onError(Throwable e); void onComplete(); } -
Observable subscribe with observer public interface Observer<T> { void onSubscribe(Disposable
d); void onNext(T t); void onError(Throwable e); void onComplete(); } -
Observable subscribe with observer public interface Observer<T> { void onSubscribe(Disposable
d); void onNext(T t); void onError(Throwable e); void onComplete(); } -
Observable subscribe with observer public interface Observer<T> { void onSubscribe(Disposable
d); void onNext(T t); void onError(Throwable e); void onComplete(); } -
Observable subscribe with consumer public interface Consumer<T> { void accept(@NonNull
T t) throws Exception; } -
Observable subscribe with consumer public interface Consumer<T> { void accept(@NonNull
T t) throws Exception; } -
What are Operators? • They are functions to create, transform,
filter, combine etc reactive source • Like builder pattern, you can chain methods, except order matters -
Merge • Combine output of multiple observables into one 1
Merge 4 3 5 1 2 3 4 5 2 -
Concat • Concatenates output of multiple observables • Subscribes to
one observable at a time and waits for current one to complete 1 Concat 4 3 5 1 2 3 4 5 2 -
FlatMap • Transform the items emitted by an Observable into
Observables • Flatten the emissions • Emissions may interleave 1 FlatMap 3 2 4 1 2 3 4 -
SwitchMap • Like flatmap • Except, mirrors recently emitted source
observable SwitchMap 1 2 2 -
ConcatMap • Like FlatMap • Except, emissions do not interleave
1 ConcatMap 3 2 4 2 1 3 4 -
Problem • Multiple API calls simultaneously • Wait for response
from each API • Apply transformation -
Zip • Combine emissions of multiple Observables • Waits for
one item from each source Zip 1 1A A 2 B 2B -
Debounce • Only emit an item from an Observable if
a particular timespan has passed without it emitting another item Debounce (500 msec) 1 3 2 4 5 1 4 5 -
What are Subject? • Broadcasts to many • Broadcasts when
no one is listening • Listens from many pc - http://www.iconsplace.com/e13491-icons/walkie-talkie-radio-icon -
Subject public abstract class Subject<T> extends Observable<T> implements Observer<T> {
} public interface Observer<T> { void onSubscribe(Disposable d); void onNext(T t); void onError(Throwable e); void onComplete(); } -
Do you really need Subject? public abstract class Subject<T> extends
Observable<T> implements Observer<T> { } public interface Observer<T> { void onSubscribe(Disposable d); void onNext(T t); void onError(Throwable e); void onComplete(); } Terminal event -
RxRelay to Rescue public abstract class Relay<T> extends Observable<T> implements
Consumer<T> { } public interface Consumer<T> { void accept(@NonNull T t) throws Exception; } -
RxRelay to Rescue public abstract class Relay<T> extends Observable<T> implements
Consumer<T> { } public interface Consumer<T> { void accept(@NonNull T t) throws Exception; } -
PublishRelay • Only emit items after observer subscribes • Login/Logout
events PublishRelay 0 2 1 3 subscribe() 1 2 2 3 3 subscribe() -
BehaviorRelay • Emits most recent item and all subsequent items
BehaviorRelay 0 2 1 3 1 2 2 3 3 0 1 subscribe() subscribe() -
Legacy code with callback public interface GetLocationCallback { void onSuccess(@NonNull
Location location); void onFailure(@Nullable Status locationSettingsStatus); } public class LocationService { public void getCurrentLocation(final GetLocationCallback newPendingLocationRequest) { } } -
Source wraps callback with create public Single<Location> getCurrentLocation() { return
Single.create(emitter -> { final GetLocationCallback callback = new GetLocationCallback() { @Override public void onSuccess(@NonNull Location location) { emitter.onSuccess(location); } @Override public void onFailure(@Nullable Status locationSettingsStatus) { emitter.onError(new LocationServiceException(locationSettingsStatus)); } }; getCurrentLocation(callback); }); } -
Source wraps callback with create public Single<Location> getCurrentLocation() { return
Single.create(emitter -> { final GetLocationCallback callback = new GetLocationCallback() { @Override public void onSuccess(@NonNull Location location) { emitter.onSuccess(location); } @Override public void onFailure(@Nullable Status locationSettingsStatus) { emitter.onError(new LocationServiceException(locationSettingsStatus)); } }; getCurrentLocation(callback); }); } -
Source wraps callback with create public Single<Location> getCurrentLocation() { return
Single.create(emitter -> { final GetLocationCallback callback = new GetLocationCallback() { @Override public void onSuccess(@NonNull Location location) { emitter.onSuccess(location); } @Override public void onFailure(@Nullable Status locationSettingsStatus) { emitter.onError(new LocationServiceException(locationSettingsStatus)); } }; getCurrentLocation(callback); }); } -
Source wraps callback with create public Single<Location> getCurrentLocation() { return
Single.create(emitter -> { final GetLocationCallback callback = new GetLocationCallback() { @Override public void onSuccess(@NonNull Location location) { emitter.onSuccess(location); } @Override public void onFailure(@Nullable Status locationSettingsStatus) { emitter.onError(new LocationServiceException(locationSettingsStatus)); } }; getCurrentLocation(callback); }); } -
Source wraps function with fromCallable Single.fromCallable(() -> someHeavyComputation()); • Defers
execution until subscription • Handles checked exception • Invokes function for each observer that subscribes -
Types of Schedulers Method Description # of Thread computation Event
loops, callbacks and computation work Available processors io Asynchronously blocking IO Unbound newThread Casual use Unbound -
Defaults to current thread Observable.fromCallable(() -> getName()) // On Main
Thread .doOnNext(id -> {}) // On Main Thread .subscribe() // On Main Thread -
subscribeOn Observable.fromCallable(() -> getName()) // Computation Thread .subscribeOn(Schedulers.computation()) .doOnNext(id ->
{}) // Computation Thread .subscribe() -
subscribeOn Observable.fromCallable(() -> getName()) // Computation Thread .subscribeOn(Schedulers.computation()) .doOnNext(id ->
{}) // Computation Thread .subscribe() // Computation Thread -
Multiple subscribeOn Observable.fromCallable(() -> getName()) // Computation Thread .subscribeOn(Schedulers.computation()) .subscribeOn(Schedulers.io())
.doOnNext(id -> {}) // Computation Thread .subscribe() -
Multiple subscribeOn Observable.fromCallable(() -> getName()) // Computation Thread .subscribeOn(Schedulers.computation()) .subscribeOn(Schedulers.io())
.doOnNext(id -> {}) // Computation Thread .subscribe() // Computation Thread -
Multiple subscribeOn Observable.fromCallable(() -> getName()) // Computation Thread .subscribeOn(Schedulers.computation()) .subscribeOn(Schedulers.io())
// Has no impact .doOnNext(id -> {}) // Computation Thread .subscribe() // Computation Thread -
subscribeOn + observeOn Observable.fromCallable(() -> getName()) // Computation Thread .subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread()) .doOnNext(id -> {}) .subscribe() -
subscribeOn + observeOn Observable.fromCallable(() -> getName()) // Computation Thread .subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread()) .doOnNext(id -> {}) // Main Thread .subscribe() -
subscribeOn + observeOn Observable.fromCallable(() -> getName()) // Computation Thread .subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread()) .doOnNext(id -> {}) // Main Thread .subscribe() // Main Thread -
subscribeOn + observeOn + observeOn Observable.fromCallable(() -> getName()) .subscribeOn(Schedulers.computation()) .observeOn(Schedulers.io())
.doOnNext(id -> {}) .observeOn(AndroidSchedulers.mainThread()) .subscribe() -
subscribeOn + observeOn + observeOn Observable.fromCallable(() -> getName()) // Computation
Thread .subscribeOn(Schedulers.computation()) .observeOn(Schedulers.io()) .doOnNext(id -> {}) .observeOn(AndroidSchedulers.mainThread()) .subscribe() -
subscribeOn + observeOn + observeOn Observable.fromCallable(() -> getName()) // Computation
Thread .subscribeOn(Schedulers.computation()) .observeOn(Schedulers.io()) .doOnNext(id -> {}) // IO Thread .observeOn(AndroidSchedulers.mainThread()) .subscribe() -
subscribeOn + observeOn + observeOn Observable.fromCallable(() -> getName()) // Computation
Thread .subscribeOn(Schedulers.computation()) .observeOn(Schedulers.io()) .doOnNext(id -> {}) // IO Thread .observeOn(AndroidSchedulers.mainThread()) .subscribe() // Main Thread -
Architecture View state Repository Use case Presenter View Presentation Layer
Domain Layer Data Layer Observable<T> Observable<T> Observable<T> -
Cloud Store discountCloudStore .fetchNearbyDiscount(NearbyRequestBody(lat, lng))// Single<NearbyResponse> .filter { it.nearbyMerchants.isNotEmpty() }
.map { it.nearbyMerchants } .doOnSuccess { discountCacheStore.updateNearbyCache(it) } -
Cloud Store discountCloudStore .fetchNearbyDiscount(NearbyRequestBody(lat, lng))// Single<NearbyResponse> .filter { it.nearbyMerchants.isNotEmpty() }
// Maybe<NearbyResponse> .map { it.nearbyMerchants } .doOnSuccess { discountCacheStore.updateNearbyCache(it) } -
Cloud Store discountCloudStore .fetchNearbyDiscount(NearbyRequestBody(lat, lng))// Single<NearbyResponse> .filter { it.nearbyMerchants.isNotEmpty() }
// Maybe<NearbyResponse> .map { it.nearbyMerchants } // Maybe<List<Merchants>> .doOnSuccess { discountCacheStore.updateNearbyCache(it) } -
Cloud Store discountCloudStore .fetchNearbyDiscount(NearbyRequestBody(lat, lng))// Single<NearbyResponse> .filter { it.nearbyMerchants.isNotEmpty() }
// Maybe<NearbyResponse> .map { it.nearbyMerchants } // Maybe<List<Merchants>> .doOnSuccess { discountCacheStore.updateNearbyCache(it) } // Side effect -
Architecture – Domain Layer View state Repository Use case Presenter
View public interface WalletUseCase<I, O> { O execute(I input); } -
Declaring view state sealed class DiscountsViewState { object Loading :
DiscountsViewState() data class Error(val error: Throwable) : DiscountsViewState() data class DataReady(val merchantWrappers: List<MerchantWrapper>) :DiscountsViewState() } -
Declaring view state sealed class DiscountsViewState { object Loading :
DiscountsViewState() data class Error(val error: Throwable) : DiscountsViewState() data class DataReady(val merchantWrappers: List<MerchantWrapper>) :DiscountsViewState() } -
Declaring view state sealed class DiscountsViewState { object Loading :
DiscountsViewState() data class Error(val error: Throwable) : DiscountsViewState() data class DataReady(val merchantWrappers: List<MerchantWrapper>) :DiscountsViewState() } -
onDestroy onDestroy onDetach onDetach onAttach onAttach onCreate onCreate Presenter View
Exposes PublishRelay as observable for input Subscribes to BehaviorRelay and updates view Dispose composite disposable for UI Dispose composite disposable for Presenter -
Presenter View Presentation Layer onAttach Presenter View onDetach Data is
received Requests Data Creates UI View State Passes to BehaviorRelay -
Presenter View Presentation Layer onAttach Presenter View onDetach Data is
received Requests Data Presenter View onAttach Subscribes to BehaviorRelay Updates UI with missed view state Only distinct view state Creates UI View State Passes to BehaviorRelay -
Presenter – onCreate compositePresenterDisposable += fetchNearbyCoupons // PublishRelay - to
initiate stream .flatMap { fetchNearbyDiscountsUseCase .execute() // Maybe<List<MerchantWrapper>> } // DiscountViewState -
Presenter – onCreate compositePresenterDisposable += fetchNearbyCoupons // PublishRelay - to
initiate stream .flatMap { fetchNearbyDiscountsUseCase .execute() // Maybe<List<MerchantWrapper>> .toObservable() // Maybe to Observable } // DiscountViewState -
Presenter – onCreate compositePresenterDisposable += fetchNearbyCoupons // PublishRelay - to
initiate stream .flatMap { fetchNearbyDiscountsUseCase .execute() // Maybe<List<MerchantWrapper>> .toObservable() // Maybe to Observable .map { DiscountsViewState.DataReady(it) } // Transform } // DiscountViewState -
Presenter – onCreate compositePresenterDisposable += fetchNearbyCoupons // PublishRelay - to
initiate stream .flatMap { fetchNearbyDiscountsUseCase .execute() // Maybe<List<MerchantWrapper>> .toObservable() // Maybe to Observable .map { DiscountsViewState.DataReady(it) } // Transform .onErrorReturn { t: Throwable -> DiscountsViewState.Error(t) } // handle error } // DiscountViewState -
Presenter – onCreate compositePresenterDisposable += fetchNearbyCoupons // PublishRelay - to
initiate stream .flatMap { fetchNearbyDiscountsUseCase .execute() // Maybe<List<MerchantWrapper>> .toObservable() // Maybe to Observable .map { DiscountsViewState.DataReady(it) } // Transform .onErrorReturn { t: Throwable -> DiscountsViewState.Error(t) } // handle error .startWith(DiscountsViewState.Loading) } // DiscountViewState -
Presenter – onCreate compositePresenterDisposable += fetchNearbyCoupons // PublishRelay - to
initiate stream .flatMap { fetchNearbyDiscountsUseCase .execute() // Maybe<List<MerchantWrapper>> .toObservable() // Maybe to Observable .map { DiscountsViewState.DataReady(it) } // Transform .onErrorReturn { t: Throwable -> DiscountsViewState.Error(t) } // handle error .startWith(DiscountsViewState.Loading) } // DiscountViewState .observeOn(AndroidSchedulers.mainThread()) // RxAndroid – Main Thread -
Presenter – onCreate compositePresenterDisposable += fetchNearbyCoupons // PublishRelay - to
initiate stream .flatMap { fetchNearbyDiscountsUseCase .execute() // Maybe<List<MerchantWrapper>> .toObservable() // Maybe to Observable .map { DiscountsViewState.DataReady(it) } // Transform .onErrorReturn { t: Throwable -> DiscountsViewState.Error(t) } // handle error .startWith(DiscountsViewState.Loading) } // DiscountViewState .observeOn(AndroidSchedulers.mainThread()) // RxAndroid – Main Thread .subscribe({ viewState -> statesBehaviorRelay.accept(viewState) }, { // processError }) -
Presenter – onCreate compositePresenterDisposable += fetchNearbyCoupons // PublishRelay - to
initiate stream .flatMap { fetchNearbyDiscountsUseCase .execute() // Maybe<List<MerchantWrapper>> .toObservable() // Maybe to Observable .map { DiscountsViewState.DataReady(it) } // Transform .onErrorReturn { t: Throwable -> DiscountsViewState.Error(t) } // handle error .startWith(DiscountsViewState.Loading) } // DiscountViewState .observeOn(AndroidSchedulers.mainThread()) // RxAndroid – Main Thread .subscribe({ viewState -> statesBehaviorRelay.accept(viewState) }, { // processError }) -
Presenter - onAttach compositeUiDisposable += states // BehaviorRelay .distinctUntilChanged() .observeOn(AndroidSchedulers.mainThread())
.subscribe({ viewState -> view.render(viewState) }) -
Composite Disposable – clear Vs dispose • Clear will dispose
all added disposables • Dispose is like clear except you can not add any more disposables -
Blogs to bookmark • Jake Wharton - http://jakewharton.com/blog/ • Dan
Lew - http://blog.danlew.net/ • Kaushik Gopal - https://kaush.co/ • David Karnok - http://akarnokd.blogspot.com/ -
What are Subjects • Inherit Observable and implements Observer •
Hot Observables • toSerialized() to make Observer method thread safe • Type of Subjects • PublishSubject • BehaviorSubject • ReplaySubject • AsyncSubject -
Architecture – Presentation Layer • Presenter is aware when view
is attached and detached • Presenter creates view states and passes it to BehaviorRelay • Whenever view is attached it gets its states from BehaviorRelay