Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Subscribe RxJava vs LiveData English
Search
Bruno Aybar
October 20, 2018
Programming
0
130
Subscribe RxJava vs LiveData English
2018 edition, in English
Bruno Aybar
October 20, 2018
Tweet
Share
More Decks by Bruno Aybar
See All by Bruno Aybar
Compose: Estados y Recomposición
bruno125
0
29
Annotation Processors vs Kotlin Plugins
bruno125
0
50
Understanding Kotlin Type System
bruno125
1
52
Subscribe { RxJava vs LiveData }
bruno125
1
280
Yo también quiero usar Kotlin
bruno125
0
280
Kotlin en Fandango Latam
bruno125
0
150
Android Custom Views
bruno125
0
200
Developing a Fan Made Version Of My University's App
bruno125
0
100
Other Decks in Programming
See All in Programming
fs2-io を試してたらバグを見つけて直した話
chencmd
0
230
なまけものオバケたち -PHP 8.4 に入った新機能の紹介-
tanakahisateru
1
120
Refactor your code - refactor yourself
xosofox
1
260
Effective Signals in Angular 19+: Rules and Helpers
manfredsteyer
PRO
0
100
今年一番支援させていただいたのは認証系サービスでした
satoshi256kbyte
1
250
Recoilを剥がしている話
kirik
5
6.7k
暇に任せてProxmoxコンソール 作ってみました
karugamo
2
720
ゆるやかにgolangci-lintのルールを強くする / Kyoto.go #56
utgwkk
2
380
Асинхронность неизбежна: как мы проектировали сервис уведомлений
lamodatech
0
760
rails stats で紐解く ANDPAD のイマを支える技術たち
andpad
1
290
Symfony Mapper Component
soyuka
2
730
テストコード文化を0から作り、変化し続けた組織
kazatohiei
2
1.5k
Featured
See All Featured
Code Reviewing Like a Champion
maltzj
520
39k
Rebuilding a faster, lazier Slack
samanthasiow
79
8.7k
Agile that works and the tools we love
rasmusluckow
328
21k
Unsuck your backbone
ammeep
669
57k
ピンチをチャンスに:未来をつくるプロダクトロードマップ #pmconf2020
aki_iinuma
111
49k
Keith and Marios Guide to Fast Websites
keithpitt
410
22k
GitHub's CSS Performance
jonrohan
1030
460k
Building Flexible Design Systems
yeseniaperezcruz
327
38k
A designer walks into a library…
pauljervisheath
204
24k
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
32
2.7k
Docker and Python
trallard
42
3.1k
The Art of Programming - Codeland 2020
erikaheidi
53
13k
Transcript
Subscribe { RxJava vs LiveData }
@brunoaybarg @bruno.aybar Bruno125 Bruno Aybar Android Dev Peru Organizer Android
Engineer
• Allow us to observe changes over some kind of
data, and to react to those changes. • Propose a reactive paradigm • Do they do the same? RxJava & LiveData
OBSERVER pattern
OBSERVER pattern Design pattern that defines a dependency between objects
(…), in which one of them changes its state, it notifies about it to all of its dependants
OBSERVER RxJava LiveData pattern
RxJava
RxJava An API for asynchronous programming with observable streams Is
a combination of the best ideas from the Observer pattern, the Iterator pattern, and functional programming ReactiveX RxJava RxSwift RxJS Rx.NET RxPY RxPHP …
Stream of Data states events data data data
Fuente: Imagen tomada de https://www.pinterest.com/pin/749708669188692420/
Subscriber<T>
Observable<T>
Flowable<T> RxJava 2:
package org.reactivestreams; public interface Subscriber<T> { public void onNext(T
t); public void onError(Throwable t); public void onComplete(); }
Flowable.just(1)
Flowable.just(1) Flowable.fromArray(1,2,3)
Flowable.create<Int>({ s -> }, BackpressureStrategy.BUFFER) Flowable.fromArray(1,2,3) Flowable.just(1)
Flowable.create<Int>({ s -> s.onNext(1) }, BackpressureStrategy.BUFFER) Flowable.fromArray(1,2,3)
Flowable.just(1)
Flowable.create<Int>({ s -> s.onNext(1) s.onNext(2) }, BackpressureStrategy.BUFFER) Flowable.just(1)
Flowable.fromArray(1,2,3)
Flowable.create<Int>({ s -> s.onNext(1) s.onNext(2) s.onNext(3) }, BackpressureStrategy.BUFFER) Flowable.just(1)
Flowable.fromArray(1,2,3)
Flowable.create<Int>({ s -> s.onNext(1) s.onNext(2) s.onNext(3) s.onComplete() }, BackpressureStrategy.BUFFER)
Flowable.just(1) The stream ends here! Flowable.fromArray(1,2,3)
Flowable.create<Int>({ s -> s.onNext(1) s.onNext(2) s.onNext(3) s.onComplete() s.onNext(4) }, BackpressureStrategy.BUFFER)
Flowable.just(1) Not emitted Flowable.fromArray(1,2,3)
Flowable.create<Int>({ s -> s.onNext(1) s.onNext(2) s.onNext(3) s.onError(Throwable(“Error!")) s.onNext(4) }, BackpressureStrategy.BUFFER)
Flowable.just(1) Not emitted Flowable.fromArray(1,2,3)
Flowable.fromArray(1,2,3) Flowable.create<Int>({ s -> // heavy transaction... // async operation...
}, BackpressureStrategy.BUFFER) Flowable.just(1)
Event subscription
Flowable.just(1).subscribe( { value -> log("onNext: $value") }, { error ->
log("onError: $error")}, { log("onComplete!") } )
Flowable.just(1).subscribe( { value -> log("onNext: $value") }, { error ->
log("onError: $error")}, { log("onComplete!") } )
val subscription = Flowable.just(1).subscribe( { value -> log("onNext: $value") },
{ error -> log("onError: $error")}, { log("onComplete!") } ) subscription.dispose()
Handling Threads
Controller UI DataSource
Controller Presenter ViewModel DataSource UI
Controller DataSource UI
Controller DataSource UI Background
Controller DataSource UI UI Thread
Flowable.just(1).subscribe( { value -> log("onNext: $value") }, { error ->
log("onError: $error")}, { log("onComplete!") } )
Flowable.just(1) .subscribeOn(Schedulers.computation()) .subscribe( { value -> log("onNext: $value") }, {
error -> log("onError: $error")}, { log("onComplete!") } ) Thread in which the operation will be performed
Flowable.just(1) .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { value -> log("onNext: $value") },
{ error -> log("onError: $error")}, { log("onComplete!") } ) Thread in which we will listen to the stream emissions
Operations
Flowable.fromArray(1,2,3,4) .filter { it % 2 == 0 }
Flowable.fromArray(1,2,3,4) .filter { it % 2 == 0 } .map
{ it + 10 } Flowable.just(User(“1”, “Bruno”)) .map { it.name }
Combine CombineLatest And/Then/When Zip Switch Join ... Filtering Filter Distinct
First Last Take ... Transform Map FlatMap Scan GroupBy Buffer ... More: http:/ /reactivex.io/documentation/ operators.html
Steep learning curve
LiveData
LiveData Room Lifecycle ViewModel ARCHITECTURE COMPONENTS
LiveData Lifecycle +
Flowable.fromArray(1,2,3)
Flowable.fromArray(1,2,3) 1 2 3 LiveData<Int>
Flowable.fromArray(1,2,3) 1 2 3 MutableLiveData<Integer> data = new MutableLiveData<>();
data.setValue(1); //UI thread data.setValue(2); //UI thread data.postValue(3); //Background thread
Flowable.fromArray(1,2,3) 1 2 3 MutableLiveData<Integer> data = new MutableLiveData<>();
data.setValue(1); //UI thread data.setValue(2); //UI thread data.postValue(3); //Background thread
Event subscription
data.observe(lifecycleOwner, new Observer<Integer>() { @Override public void onChanged(@Nullable Integer value)
{ log("onChanged: $value”) } });
data.observe(lifecycleOwner, Observer<Int> { value -> log("onChanged: $value”) })
data.observe(lifecycleOwner, Observer<Int> { value -> log("onChanged: $value”) })
data.observe(lifecycleOwner, Observer<Int> { value -> log("onChanged: $value”) })
None
LifecycleOwner class that contains information about a component lifecycle, and
allow other objects to observe its changes
LifecycleOwner class that contains information about a component lifecycle, and
allow other objects to observe its changes Destroyed Created Started Resumed Initialized
None
LifecycleObserver allows you to observe the current state of a
LifecycleOwner
LifecycleObserver public class MyObserver implements LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public
void connectListener() { } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) public void disconnectListener() { } }
Flowable <Int> Activity 1 2 3 subscribes to data.subscribe {
value -> textView.setText("Text " + value) }
Flowable <Int> Activity subscribes to data.subscribe { value -> textView.setText("Text
" + value) } destroyed 4 5 6
LiveData <Int> Activity subscribes to data.observe(lifecycleOwner, { value -> textView.setText("Text
" + value) }) destroyed X
LiveData <Int> Activity subscribes to data.observe(lifecycleOwner, { value -> textView.setText("Text
" + value) }) STARTED | RESUMED
LiveData <Int> Activity subscribes to data.observe(lifecycleOwner, { value -> textView.setText("Text
" + value) }) STARTED | RESUMED 6
Handling threads
MutableLiveData<Integer> data = new MutableLiveData<>(); data.setValue(1); //UI thread data.postValue(2);
//Background thread
MutableLiveData<Integer> data = new MutableLiveData<>(); data.setValue(1); //UI thread data.postValue(2);
//Background thread data.observe(lifecycleOwner, { value -> // executes in UI thread })
Operations
val userLiveData: LiveData<User> = … val userNameLiveData = Transformations.map(
userLiveData, { it.name }) Map SwitchMap Custom Transformations
+ LiveData Lifecycle + ViewModel + Room
RxJava vs LiveData Explicit code ✔ Thread handling ✔ Powerful
Operators ✔ Steep learning curve ✘ Really simple ✔ Android-oriented ✔ Integration with AC ✔ Not so powerful operators ✘ Library compatibility (i.e. Retrofit) ✔ Over-engineered? ✘ Portable knowledge ✔
¯\_(ツ)_/¯ RxJava vs LiveData
Controller Presenter ViewModel Data Sources UI
Controller Presenter ViewModel Data Sources UI LiveData
Controller Presenter ViewModel Data Sources UI RxJava
¯\_(ツ)_/¯ RxJava vs LiveData
Additional Material Intro to RxJava (Christina Lee) https:/ /www.youtube.com/watch?v=XLH2v9deew0 Learning
Rx (for Android) by Example https:/ /www.youtube.com/watch?v=k3D0cWyNno4 Common RxJava Mistakes https:/ /www.youtube.com/watch?v=QdmkXL7XikQ RxJava in Baby Steps https:/ /www.youtube.com/watch?v=YPf6AYDaYf8 RxMarbles http:/ /rxmarbles.com/
Live Data docs https:/ /developer.android.com/topic/libraries/architecture/livedata.html LiveData & Lifecycle https:/ /www.youtube.com/watch?v=jCw5ib0r9wg
ViewModels, LiveData and Lifecycles, oh my! https:/ /www.youtube.com/watch?v=SlZVYkhoSq8 Android lifecycle-aware components codelab https:/ /codelabs.developers.google.com/codelabs/android-lifecycles Additional Material
@brunoaybarg @bruno.aybar Bruno125 Bruno Aybar Android Dev Perú Organizer Android
Engineer @ Avantica Gracias! https://speakerdeck.com/bruno125/subscribe-rxjava-vs-livedata-2018