Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ReactiveX - escolha sua plataforma

ReactiveX - escolha sua plataforma

Apresentação sobre duas libs de RX: RxJava e RxJS

Ruiter Matos

December 08, 2017
Tweet

More Decks by Ruiter Matos

Other Decks in Technology

Transcript

  1. 5 motivos 1. Intuitivo 2. Expansível 3. Código limpo 4.

    Concorrencia 5. Resolução de problemas
  2. 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") }
  3. 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("") } })
  4. • Map • Zip • Filter • FlatMap • Take

    • Skip • Buffer • Concat • Replay • Merge
  5. 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()
  6. 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") }
  7. Exemplo interface APIClient { @PUT("my/api/updatepath") fun updateMyData(@Body data: MyData): Completable

    } apiClient.updateMyData(myUpdatedData) .subscribe({ // handle completion }, { throwable -> // handle error })
  8. Maybe Semelhante ao Single e Completable, a diferença é que

    seu consumidor vai receber apenas 0 ou 1.
  9. Exemplo Maybe.just(1) .map { v -> v + 1 }

    .filter { v -> v == 1 } .defaultIfEmpty(2) .test() .assertResult(2)
  10. Introdução O RxJS é uma biblioteca que nos permite criar

    e manipular facilmente fluxos de eventos e dados.
  11. 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(); }});
  12. Com Rx @Injectable() class UserService { ... getUsers(): Observable<User[]> {

    return this.http.get(myApiUrl) .map(res=>res.json()) .catch(err=>{ throw new Error(err.message); }); } … }
  13. 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 } });
  14. Cancelando assinatura var observable = Rx.Observable.from([10, 20, 30]); var subscription

    = observable.subscribe(x => console.log(x)); subscription.unsubscribe();
  15. 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));
  16. Map var clicks = Rx.Observable.fromEvent(document, 'click'); var positions = clicks.map(ev

    => ev.clientX); positions.subscribe(x => console.log(x));