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
51
Subscribe { RxJava vs LiveData }
bruno125
1
280
Yo también quiero usar Kotlin
bruno125
0
270
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
Tuning GraphQL on Rails
pyama86
2
1k
GitHub Actionsのキャッシュと手を挙げることの大切さとそれに必要なこと
satoshi256kbyte
5
380
Boost Performance and Developer Productivity with Jakarta EE 11
ivargrimstad
0
790
macOS でできる リアルタイム動画像処理
biacco42
3
1.4k
弊社の「意識チョット低いアーキテクチャ」10選
texmeijin
5
23k
Generative AI Use Cases JP (略称:GenU)奮闘記
hideg
0
150
PagerDuty を軸にした On-Call 構築と運用課題の解決 / PagerDuty Japan Community Meetup 4
horimislime
1
110
Universal Linksの実装方法と陥りがちな罠
kaitokudou
1
220
シールドクラスをはじめよう / Getting Started with Sealed Classes
mackey0225
3
390
Honoの来た道とこれから
yusukebe
19
3k
[PyCon Korea 2024 Keynote] 커뮤니티와 파이썬, 그리고 우리
beomi
0
110
現場で役立つモデリング 超入門
masuda220
PRO
12
2.9k
Featured
See All Featured
Optimising Largest Contentful Paint
csswizardry
33
2.9k
A Tale of Four Properties
chriscoyier
156
23k
Build The Right Thing And Hit Your Dates
maggiecrowley
32
2.4k
Automating Front-end Workflow
addyosmani
1365
200k
Helping Users Find Their Own Way: Creating Modern Search Experiences
danielanewman
29
2.2k
YesSQL, Process and Tooling at Scale
rocio
167
14k
jQuery: Nuts, Bolts and Bling
dougneiner
61
7.5k
Performance Is Good for Brains [We Love Speed 2024]
tammyeverts
3
370
Fantastic passwords and where to find them - at NoRuKo
philnash
50
2.8k
Thoughts on Productivity
jonyablonski
67
4.3k
Building a Scalable Design System with Sketch
lauravandoore
459
33k
Raft: Consensus for Rubyists
vanstee
136
6.6k
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