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

Subscribe { RxJava vs LiveData }

Bruno Aybar
November 25, 2017

Subscribe { RxJava vs LiveData }

Bruno Aybar

November 25, 2017
Tweet

More Decks by Bruno Aybar

Other Decks in Technology

Transcript

  1. • Trending entre Android devs • Nos permiten observar cambios

    sobre algún tipo de información, y operar sobre ellos • Proponen un paradigma distinto al convencional • ¿Hacen lo mismo? RxJava y LiveData
  2. OBSERVER pattern Es un patrón de diseño de software que

    define una dependencia entre objetos (…), de manera que cuando uno de los objetos cambia su estado, notifica este cambio a todos los dependientes
  3. 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 …
  4. package org.reactivestreams; public interface Subscriber<T> {
 
 public void onNext(T

    t);
 
 public void onError(Throwable t);
 
 public void onComplete();
 }

  5. Flowable.fromArray(1,2,3) Flowable.create<Int>({ s ->
 // heavy transaction... // async operation...

    }, BackpressureStrategy.BUFFER) Flowable.just(1) no es la mejor idea…
  6. Flowable.just(1).subscribe(
 { value -> log("onNext: $value") },
 { error ->

    log("onError: $error")},
 { log("onComplete!") }
 ) Kotlin ❤ (o Retrolambda, en su defecto)
  7. Flowable.just(1).subscribe(new Consumer<Integer>() {
 @Override
 public void accept(Integer integer) throws Exception

    {
 log("onNext: " + integer);
 }
 }, new Consumer<Throwable>() {
 @Override
 public void accept(Throwable throwable) throws Exception {
 log("onError" + throwable);
 }
 }, new Action() {
 @Override
 public void run() throws Exception {
 log("onComplete!");
 }
 }); Java
  8. Flowable.just(1).subscribe(
 { value -> log("onNext: $value") },
 { error ->

    log("onError: $error")},
 { log("onComplete!") }
 )
  9. val subscription = Flowable.just(1).subscribe(
 { value -> log("onNext: $value") },


    { error -> log("onError: $error")},
 { log("onComplete!") }
 ) subscription.dispose()
  10. Flowable.just(1).subscribe(
 { value -> log("onNext: $value") },
 { error ->

    log("onError: $error")},
 { log("onComplete!") }
 )
  11. Flowable.just(1)
 .subscribeOn(Schedulers.computation()) .subscribe(
 { value -> log("onNext: $value") },
 {

    error -> log("onError: $error")},
 { log("onComplete!") }
 ) Hilo (Thread) en el que se realizará la operación
  12. Flowable.just(1)
 .subscribeOn(Schedulers.computation())
 .observeOn(AndroidSchedulers.mainThread()) .subscribe(
 { value -> log("onNext: $value") },


    { error -> log("onError: $error")},
 { log("onComplete!") }
 ) Hilo (Thread) en el que se escuchará el resultado
  13. Flowable.fromArray(1,2,3,4)
 .filter { it % 2 == 0 }
 .map

    { it + 10 } Flowable.just(User(“1”, “Bruno”))
 .map { it.name }
  14. 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
  15. 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
  16. 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
  17. LifecycleOwner es una clase que contiene información sobre el ciclo

    de vida de un componente, y permite a otros objetos observar su estado
  18. LifecycleOwner es una clase que contiene información sobre el ciclo

    de vida de un componente, y permite a otros objetos observar su estado Destroyed Created Started Resumed Initialized
  19. LifecycleObserver public class MyObserver implements LifecycleObserver { 
 @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
 public

    void connectListener() {
 
 }
 
 @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
 public void disconnectListener() {
 
 }
 }

  20. Flowable
 <Int> Activity 1 2 3 se suscribe data.subscribe {

    value -> textView.setText("Text " + value) }
  21. MutableLiveData<Integer> data = 
 new MutableLiveData<>();
 data.setValue(1); //UI thread
 data.postValue(2);

    //Background thread data.observe(lifecycleOwner, { value -> // executes in UI thread })
  22. val userLiveData: LiveData<User> = … 
 val userNameLiveData = Transformations.map(

    userLiveData, { it.name }) Map SwitchMap Custom Transformations
  23. RxJava vs LiveData Simple y sencilla Operadores poderosos Manejo de

    hilos Código legible Curva de aprendizaje ✔ ✔ ✔ ✘ ✔ Enfocada a Android ✔ Integración con AC ✔ Operadores no tan 
 poderosos ✘ Compatibilidad con 
 librerías ✔ Over-engineered? ✘ Conocimiento portable ✔
  24. Material adicional 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/
  25. 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 Material adicional
  26. @brunoaybarg @bruno.aybar Bruno125 Bruno Aybar Android Lead @ Fandango Latam

    Gracias! https://speakerdeck.com/bruno125/subscribe-rxjava-vs-livedata