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
33
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
18
Android: Passado, presente e futuro.
ruiter
1
32
Other Decks in Technology
See All in Technology
社内で最大の技術的負債のリファクタリングに取り組んだお話し
kidooonn
1
550
New Relicを活用したSREの最初のステップ / NRUG OKINAWA VOL.3
isaoshimizu
2
580
Amplify Gen2 Deep Dive / バックエンドの型をいかにしてフロントエンドへ伝えるか #TSKaigi #TSKaigiKansai #AWSAmplifyJP
tacck
PRO
0
370
複雑なState管理からの脱却
sansantech
PRO
1
140
フルカイテン株式会社 採用資料
fullkaiten
0
40k
Terraform CI/CD パイプラインにおける AWS CodeCommit の代替手段
hiyanger
1
240
Taming you application's environments
salaboy
0
180
【令和最新版】AWS Direct Connectと愉快なGWたちのおさらい
minorun365
PRO
5
750
TanStack Routerに移行するのかい しないのかい、どっちなんだい! / Are you going to migrate to TanStack Router or not? Which one is it?
kaminashi
0
580
Terraform未経験の御様に対してどの ように導⼊を進めていったか
tkikuchi
2
430
エンジニア人生の拡張性を高める 「探索型キャリア設計」の提案
tenshoku_draft
1
120
強いチームと開発生産性
onk
PRO
33
11k
Featured
See All Featured
Reflections from 52 weeks, 52 projects
jeffersonlam
346
20k
Designing for Performance
lara
604
68k
The Art of Programming - Codeland 2020
erikaheidi
52
13k
Fashionably flexible responsive web design (full day workshop)
malarkey
405
65k
Practical Orchestrator
shlominoach
186
10k
Designing Dashboards & Data Visualisations in Web Apps
destraynor
229
52k
GraphQLとの向き合い方2022年版
quramy
43
13k
Stop Working from a Prison Cell
hatefulcrawdad
267
20k
Automating Front-end Workflow
addyosmani
1366
200k
What's in a price? How to price your products and services
michaelherold
243
12k
Documentation Writing (for coders)
carmenintech
65
4.4k
The Cult of Friendly URLs
andyhume
78
6k
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