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
ReactiveX - escolha sua plataforma
Search
Ruiter Matos
December 08, 2017
Technology
1
35
ReactiveX - escolha sua plataforma
Apresentação sobre duas libs de RX: RxJava e RxJS
Ruiter Matos
December 08, 2017
Tweet
Share
More Decks by Ruiter Matos
See All by Ruiter Matos
Multi Módulos em projetos Android
ruiter
1
20
Android: Passado, presente e futuro.
ruiter
1
34
Other Decks in Technology
See All in Technology
効率的な技術組織が作れる!書籍『チームトポロジー』要点まとめ
iwamot
2
190
Visual StudioとかIDE関連小ネタ話
kosmosebi
1
290
Fabric 移行時の躓きポイントと対応策
ohata_ds
1
120
Oracle Exadata Database Service(Dedicated Infrastructure):サービス概要のご紹介
oracle4engineer
PRO
0
12k
OCI技術資料 : ファイル・ストレージ 概要
ocise
3
12k
20240522 - 躍遷創作理念 @ PicCollage Workshop
dpys
0
310
深層学習と3Dキャプチャ・3Dモデル生成(土木学会応用力学委員会 応用数理・AIセミナー)
pfn
PRO
0
410
React Routerで実現する型安全なSPAルーティング
sansantech
PRO
4
890
Amazon Q Developerで.NET Frameworkプロジェクトをモダナイズしてみた
kenichirokimura
1
140
シフトライトなテスト活動を適切に行うことで、無理な開発をせず、過剰にテストせず、顧客をビックリさせないプロダクトを作り上げているお話 #RSGT2025 / Shift Right
nihonbuson
3
1.5k
Denoで作るチーム開発生産性向上のためのCLIツール
sansantech
PRO
0
140
組織に自動テストを書く文化を根付かせる戦略(2024冬版) / Building Automated Test Culture 2024 Winter Edition
twada
PRO
26
7.1k
Featured
See All Featured
The Web Performance Landscape in 2024 [PerfNow 2024]
tammyeverts
3
340
How GitHub (no longer) Works
holman
312
140k
Automating Front-end Workflow
addyosmani
1366
200k
A designer walks into a library…
pauljervisheath
205
24k
Helping Users Find Their Own Way: Creating Modern Search Experiences
danielanewman
29
2.4k
Easily Structure & Communicate Ideas using Wireframe
afnizarnur
191
16k
"I'm Feeling Lucky" - Building Great Search Experiences for Today's Users (#IAC19)
danielanewman
226
22k
Embracing the Ebb and Flow
colly
84
4.5k
Chrome DevTools: State of the Union 2024 - Debugging React & Beyond
addyosmani
3
230
XXLCSS - How to scale CSS and keep your sanity
sugarenia
248
1.3M
Why Our Code Smells
bkeepers
PRO
335
57k
Save Time (by Creating Custom Rails Generators)
garrettdimon
PRO
29
940
Transcript
ReactiveX Escolha sua plataforma
None
Porque usar Rx?
5 motivos 1. Intuitivo 2. Expansível 3. Código limpo 4.
Concorrencia 5. Resolução de problemas
None
Analogia
Observable val waterObservable = Observable.just("rain water", "river water", "lake water")
Operator val cleanWater = waterObservable.map { water -> "Clean $water"
}
Subscriber cleanWater.subscribe{ cleanWater -> Log.i("TAG", "Drink $cleanWater") }
Esqueça (for, while, if else… bla,bla) val waterSource = arrayListOf("rain
water", "river water", "lake water") for (water in waterSource) { Log.i("TAG", "Drink clean $cleanWater") }
Com Rx Observable.fromIterable(waterSource) .withIndex() .filter { it.value != "" }
.subscribe({ Log.i("checkin", "value: " + it) })
Exemplo de refatoração
Código Android editText.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable)
{} override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { if (s.length != 0) editText.setText("") } })
RxJava/RxBinding editText.textChanges().subscribe({ if (it.length != 0) editText.setText("") })
Principais Operadores
• Map • Zip • Filter • FlatMap • Take
• Skip • Buffer • Concat • Replay • Merge
RxJava 2.0
Disposable/CompositeDisposable Representa um recurso descartável. Com composite podemos utilizar o
mesmo objeto para vários recursos.
Exemplo val disposable = Single .getUsers() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ Log.i("",
"success") }, { Log.i("", "error") }) disposable.dispose() var copositeDisposable = CompositeDisposable() copositeDisposable.add(Single .getUsers() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ Log.i("", "success") }, { Log.i("", "error") })) copositeDisposable.clear()
Flowable Trata problemas com grandes quantidades de dados.
Exemplo Flowable.create<Any>({ subscriber -> var count = 0 while (true)
{ count++ subscriber.onNext(count.toString() + "\n") } }, BackpressureStrategy.DROP) .observeOn(Schedulers.newThread(), false, 3) .subscribe( { `val` -> Thread.sleep(1000) println(`val`) }, { err -> println("error ") err.printStackTrace() } ) { println("completed") }
Single Um tipo de observável que trabalha apenas com onSuccess
e onError.
Exemplo Single .getUsers() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ Log.i("", "success") }, {
Log.i("", "error") })
Completable O completable não precisa implementar um tipo de objeto
para observar.
Exemplo interface APIClient { @PUT("my/api/updatepath") fun updateMyData(@Body data: MyData): Completable
} apiClient.updateMyData(myUpdatedData) .subscribe({ // handle completion }, { throwable -> // handle error })
Maybe Semelhante ao Single e Completable, a diferença é que
seu consumidor vai receber apenas 0 ou 1.
Exemplo Maybe.just(1) .map { v -> v + 1 }
.filter { v -> v == 1 } .defaultIfEmpty(2) .test() .assertResult(2)
RxJS
Introdução O RxJS é uma biblioteca que nos permite criar
e manipular facilmente fluxos de eventos e dados.
Exemplos
Event listeners var button = document.querySelector('button'); button.addEventListener('click', () => console.log('Clicked!'));
Event listeners var button = document.querySelector('button'); Rx.Observable.fromEvent(button, 'click').subscribe(() => console.log('Clicked!'));
Flow var count = 0; var rate = 1000; var
lastClick = Date.now() - rate; var button = document.querySelector('button'); button.addEventListener('click', () => { if (Date.now() - lastClick >= rate) { console.log(`Clicked ${++count} times`); lastClick = Date.now(); }});
Em RxJS var button = document.querySelector('button'); Rx.Observable.fromEvent(button, 'click') .throttleTime(1000) .scan(count
=> count + 1, 0) .subscribe(count => console.log(`Clicked ${count} times`));
Gostou?
Vamos usar um Observable
Vamos imaginar o consumo de um web service bem comum.
Codigo em Angular getUsers(): Promise<User[]>{ return fetch(myApiUrl) .then(res=>res.json()) .catch(err=>{ throw
new Error(err.message); }); }
Com Rx @Injectable() class UserService { ... getUsers(): Observable<User[]> {
return this.http.get(myApiUrl) .map(res=>res.json()) .catch(err=>{ throw new Error(err.message); }); } … }
Ok, mas qual a vantagem?
Operadores
Subscribe getUsers() { this.userService.getUsers() .subscribe( users => this.users = users,
error => /* Tratamos erros aqui */);
Criando Observables var observable = Rx.Observable.create(function subscribe(observer) { var id
= setInterval(() => { observer.next('hi') }, 1000); });
Inscrevendo-se para Observables observable.subscribe(x => console.log(x));
Executando Observables var observable = Rx.Observable.create(function subscribe(observer) { try {
observer.next(1); observer.next(2); observer.next(3); observer.complete(); } catch (err) { observer.error(err); // delivers an error if it caught one } });
Cancelando assinatura var observable = Rx.Observable.from([10, 20, 30]); var subscription
= observable.subscribe(x => console.log(x)); subscription.unsubscribe();
Mais exemplos function multiplyByTen(input) { var output = Rx.Observable.create(function subscribe(observer)
{ input.subscribe({ next: (v) => observer.next(10 * v), error: (err) => observer.error(err), complete: () => observer.complete() }); }); return output; } var input = Rx.Observable.from([1, 2, 3, 4]); var output = multiplyByTen(input); output.subscribe(x => console.log(x));
Map var clicks = Rx.Observable.fromEvent(document, 'click'); var positions = clicks.map(ev
=> ev.clientX); positions.subscribe(x => console.log(x));
Agora é só estudar e aplicar
Referencias • http://reactivex.io/ • https://github.com/balamaci/rxjava-walkthrough • http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-map • https://medium.com/tableless/entendendo-rxjs-observable-com-angular-6f607a9a6a00
Obrigado! @ruitermatos55