$30 off During Our Annual Pro Sale. View Details »

Exploring RxJava 2 for Android (GOTOcph October 2016)

Exploring RxJava 2 for Android (GOTOcph October 2016)

This talk will be an exploration on why reactive programming works so well for Android and how to use RxJava to apply it.

Video: https://www.youtube.com/watch?v=htIXKI5gOQU

Jake Wharton
PRO

October 03, 2016
Tweet

More Decks by Jake Wharton

Other Decks in Programming

Transcript

  1. Exploring RxJava
    Jake Wharton

    View Slide

  2. Exploring RxJava 2
    Jake Wharton

    View Slide

  3. Why Reactive?
    Unless you can model your entire
    system synchronously...

    View Slide

  4. Why Reactive?
    Unless you can model your entire
    system synchronously, a single
    asynchronous source breaks
    imperative programming.

    View Slide

  5. Why Reactive?
    interface UserManager {
    User getUser();

    }A

    View Slide

  6. Why Reactive?
    interface UserManager {
    User getUser();
    void setName(String name);
    void setAge(int age);

    }A

    View Slide

  7. Why Reactive?
    interface UserManager {
    User getUser();
    void setName(String name);
    void setAge(int age);

    }A
    UserManager um = new UserManager();

    View Slide

  8. Why Reactive?
    interface UserManager {
    User getUser();
    void setName(String name);
    void setAge(int age);

    }A
    UserManager um = new UserManager();
    System.out.println(um.getUser());

    View Slide

  9. Why Reactive?
    interface UserManager {
    User getUser();
    void setName(String name);
    void setAge(int age);

    }A
    UserManager um = new UserManager();
    System.out.println(um.getUser());
    um.setName("Jane Doe");

    View Slide

  10. Why Reactive?
    interface UserManager {
    User getUser();
    void setName(String name);
    void setAge(int age);

    }A
    UserManager um = new UserManager();
    System.out.println(um.getUser());
    um.setName("Jane Doe");
    System.out.println(um.getUser());

    View Slide

  11. Why Reactive?
    interface UserManager {
    User getUser();
    void setName(String name); // <-- now async
    void setAge(int age); // <-- now async

    }A

    View Slide

  12. Why Reactive?
    interface UserManager {
    User getUser();
    void setName(String name);
    void setAge(int age);

    }A
    UserManager um = new UserManager();
    System.out.println(um.getUser());
    um.setName("Jane Doe");
    System.out.println(um.getUser());

    View Slide

  13. Why Reactive?
    interface UserManager {
    User getUser();
    void setName(String name, Runnable callback);
    void setAge(int age, Runnable callback);

    }A

    View Slide

  14. Why Reactive?
    interface UserManager {
    User getUser();
    void setName(String name, Runnable callback);A
    void setAge(int age, Runnable callback);B

    }A
    UserManager um = new UserManager();
    System.out.println(um.getUser());
    um.setName("Jane Doe", new Runnable() {
    @Override public void run() {
    System.out.println(um.getUser());
    }X
    });

    View Slide

  15. Why Reactive?
    interface UserManager {
    User getUser();
    void setName(String name, Listener listener);A
    void setAge(int age, Listener listener);B
    interface Listener {
    void success(User user);
    void failure(IOException e);
    }G

    }A

    View Slide

  16. Why Reactive?
    UserManager um = new UserManager();
    System.out.println(um.getUser());
    um.setName("Jane Doe");

    View Slide

  17. Why Reactive?
    UserManager um = new UserManager();
    System.out.println(um.getUser());
    um.setName("Jane Doe", new UserManager.Listener() {
    @Override public void success() {
    System.out.println(um.getUser());
    }A
    @Override public void failure(IOException e) {
    // TODO show the error...
    }B
    });

    View Slide

  18. Why Reactive?
    UserManager um = new UserManager();
    System.out.println(um.getUser());
    um.setName("Jane Doe", new UserManager.Listener() {
    @Override public void success() {
    System.out.println(um.getUser());
    }A
    @Override public void failure(IOException e) {
    // TODO show the error...
    }B
    });
    um.setAge(40, new UserManager.Listener() {
    @Override public void success() {
    System.out.println(um.getUser());
    }C
    2@Override public void failure(IOException e) {2
    2// TODO show the error...2
    }D
    });2

    View Slide

  19. Why Reactive?
    UserManager um = new UserManager();
    System.out.println(um.getUser());
    um.setName("Jane Doe", new UserManager.Listener() {
    @Override public void success() {
    System.out.println(um.getUser());
    um.setAge(40, new UserManager.Listener() {
    @Override public void success() {
    System.out.println(um.getUser());
    }C
    2@Override public void failure(IOException e) {2
    2// TODO show the error...2
    }D
    });2
    }A
    @Override public void failure(IOException e) {
    // TODO show the error...
    }B
    });

    View Slide

  20. Why Reactive?
    public final class UserActivity extends Activity {
    private final UserManager um = new UserManager();
    @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.user);
    TextView tv = (TextView) findViewById(R.id.user_name);
    tv.setText(um.getUser().toString());
    um.setName("Jane Doe", new UserManager.Listener() {
    @Override public void success() {
    tv.setText(um.getUser().toString());
    }A
    @Override public void failure(IOException e) {
    // TODO show the error...
    }B
    });
    }Y
    }Z

    View Slide

  21. Why Reactive?
    public final class UserActivity extends Activity {
    private final UserManager um = new UserManager();
    @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.user);
    TextView tv = (TextView) findViewById(R.id.user_name);
    tv.setText(um.getUser().toString());
    um.setName("Jane Doe", new UserManager.Listener() {
    @Override public void success() {
    tv.setText(um.getUser().toString());
    }A
    @Override public void failure(IOException e) {
    // TODO show the error...
    }B
    });
    }Y
    }Z

    View Slide

  22. Why Reactive?
    public final class UserActivity extends Activity {
    private final UserManager um = new UserManager();
    @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.user);
    TextView tv = (TextView) findViewById(R.id.user_name);
    tv.setText(um.getUser().toString());
    um.setName("Jane Doe", new UserManager.Listener() {
    @Override public void success() {
    if (isDestroyed()) {
    tv.setText(um.getUser().toString());
    }
    }A
    @Override public void failure(IOException e) {
    // TODO show the error...
    }B
    });
    }Y
    }Z

    View Slide

  23. Why Reactive?
    public final class UserActivity extends Activity {
    private final UserManager um = new UserManager();
    @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.user);
    TextView tv = (TextView) findViewById(R.id.user_name);
    tv.setText(um.getUser().toString());
    um.setName("Jane Doe", new UserManager.Listener() {
    @Override public void success() {
    if (isDestroyed()) {
    tv.setText(um.getUser().toString());
    }
    }A
    @Override public void failure(IOException e) {
    // TODO show the error...
    }B
    });
    }Y
    }Z

    View Slide

  24. Why Reactive?
    public final class UserActivity extends Activity {
    private final UserManager um = new UserManager();
    @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.user);
    TextView tv = (TextView) findViewById(R.id.user_name);
    tv.setText(um.getUser().toString());
    um.setName("Jane Doe", new UserManager.Listener() {
    @Override public void success() {
    if (isDestroyed()) {
    tv.setText(um.getUser().toString());
    }L
    }A
    @Override public void failure(IOException e) {
    // TODO show the error...
    }B
    });
    }Y
    }Z

    View Slide

  25. Why Reactive?
    public final class UserActivity extends Activity {
    private final UserManager um = new UserManager();
    @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.user);
    TextView tv = (TextView) findViewById(R.id.user_name);
    tv.setText(um.getUser().toString());
    um.setName("Jane Doe", new UserManager.Listener() {
    @Override public void success() {
    runOnUiThread(new Runnable() {
    @Override public void run() {
    if (isDestroyed()) {
    tv.setText(um.getUser().toString());
    }L
    }4
    });
    }A
    @Override public void failure(IOException e) {
    // TODO show the error...
    }B
    });
    }Y
    }Z

    View Slide

  26. Why Reactive?
    public final class UserActivity extends Activity {
    private final UserManager um = new UserManager();
    @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.user);
    TextView tv = (TextView) findViewById(R.id.user_name);
    tv.setText(um.getUser().toString());
    um.setName("Jane Doe", new UserManager.Listener() {
    @Override public void success() {
    runOnUiThread(new Runnable() {
    @Override public void run() {
    if (isDestroyed()) {
    tv.setText(um.getUser().toString());
    }
    }4
    });
    }A
    @Override public void failure(IOException e) {
    // TODO show the error...
    }B
    });
    }Y
    }Z

    View Slide

  27. Why Reactive?
    GET /
    200 OK
    SELECT *
    Jane Doe
    setText
    onClick

    View Slide

  28. Why Reactive?
    GET /
    200 OK
    SELECT *
    Jane Doe
    setText
    onClick

    View Slide

  29. Why Reactive?
    GET /
    200 OK
    SELECT *
    Jane Doe
    setText
    onClick

    View Slide

  30. Why Reactive?
    GET /
    200 OK
    SELECT *
    Jane Doe
    setText
    onClick

    View Slide

  31. Why Reactive?
    GET /
    200 OK
    SELECT *
    Jane Doe
    setText
    onClick

    View Slide

  32. Why Reactive?

    View Slide

  33. Why Reactive?

    View Slide

  34. Why Reactive?
    Unless you can model your entire
    system synchronously, a single
    asynchronous source breaks
    imperative programming.

    View Slide

  35. Why Reactive?

    View Slide

  36. Why Reactive?

    View Slide

  37. Why Reactive?

    View Slide

  38. Why Reactive?

    View Slide

  39. Why Reactive?

    View Slide

  40. Why Reactive?

    View Slide

  41. RxJava

    View Slide

  42. RxJava
    • A set of classes for representing sources of data.

    View Slide

  43. RxJava
    • A set of classes for representing sources of data.
    • A set of classes for listening to data sources.

    View Slide

  44. RxJava
    • A set of classes for representing sources of data.
    • A set of classes for listening to data sources.
    • A set of methods for modifying and composing the data.

    View Slide

  45. RxJava
    • A set of classes for representing sources of data.
    • A set of classes for listening to data sources.
    • A set of methods for modifying and composing the data.

    View Slide

  46. Sources

    View Slide

  47. Sources
    • Usually do work when you start or stop listening.

    View Slide

  48. Sources
    • Usually do work when you start or stop listening.
    • Synchronous or asynchronous.

    View Slide

  49. Sources
    • Usually do work when you start or stop listening.
    • Synchronous or asynchronous.
    • Single item or many items.

    View Slide

  50. Sources
    • Usually do work when you start or stop listening.
    • Synchronous or asynchronous.
    • Single item, many items, or empty.

    View Slide

  51. Sources
    • Usually do work when you start or stop listening.
    • Synchronous or asynchronous.
    • Single item, many items, or empty.
    • Terminates with an error or succeeds to completion.

    View Slide

  52. Sources
    • Usually do work when you start or stop listening.
    • Synchronous or asynchronous.
    • Single item, many items, or empty.
    • Terminates with an error or succeeds to completion.
    • May never terminate!

    View Slide

  53. Sources
    • Usually do work when you start or stop listening.
    • Synchronous or asynchronous.
    • Single item, many items, or empty.
    • Terminates with an error or succeeds to completion.
    • May never terminate!
    • Just an implementation of the Observer pattern.

    View Slide

  54. • Observable
    • Flowable
    void
    void

    Sources

    View Slide

  55. • Observable
    • Emits 0 to n items.
    • Terminates with complete or error.
    • Flowable
    • Emits 0 to n items.
    • Terminates with complete or error.
    void
    void

    Sources

    View Slide

  56. • Observable
    • Emits 0 to n items.
    • Terminates with complete or error.
    • Does not have backpressure.
    • Flowable
    • Emits 0 to n items.
    • Terminates with complete or error.
    • Has backpressure.
    void
    void

    Sources

    View Slide

  57. Flowable vs. Observable

    View Slide

  58. Flowable vs. Observable
    • Backpressure allows you to control how fast a source emits items.

    View Slide

  59. Flowable vs. Observable
    • Backpressure allows you to control how fast a source emits items.
    • RxJava 1.x added backpressure late in the design process.

    View Slide

  60. Flowable vs. Observable
    • Backpressure allows you to control how fast a source emits items.
    • RxJava 1.x added backpressure late in the design process.
    • All types exposed backpressure but not all sources respected it.

    View Slide

  61. Flowable vs. Observable
    • Backpressure allows you to control how fast a source emits items.
    • RxJava 1.x added backpressure late in the design process.
    • All types exposed backpressure but not all sources respected it.
    • Backpressure, like inheritance, must be designed for.

    View Slide

  62. Flowable vs. Observable
    • Backpressure, like inheritance, must be designed for.

    View Slide

  63. Flowable vs. Observable
    • Backpressure, like inheritance, must be designed for.
    Observable events
    = RxView.touches(paintView);

    View Slide

  64. Flowable vs. Observable
    • Backpressure, like inheritance, must be designed for.
    Observable events
    = RxView.touches(paintView);
    Observable rows
    = db.createQuery("SELECT * …");

    View Slide

  65. Flowable vs. Observable
    • Backpressure, like inheritance, must be designed for.
    Observable events
    = RxView.touches(paintView);
    Observable rows
    = db.createQuery("SELECT * …");

    View Slide

  66. Flowable vs. Observable
    • Backpressure, like inheritance, must be designed for.
    Observable events
    = RxView.touches(paintView);
    Observable rows
    = db.createQuery("SELECT * …");

    View Slide

  67. Flowable vs. Observable
    • Backpressure, like inheritance, must be designed for.
    Observable events
    = RxView.touches(paintView);
    Observable rows
    = db.createQuery("SELECT * …");

    View Slide

  68. Flowable vs. Observable
    • Backpressure, like inheritance, must be designed for.
    Observable events
    = RxView.touches(paintView);
    Observable rows
    = db.createQuery("SELECT * …");
    MissingBackpressureException

    View Slide

  69. Flowable vs. Observable
    • Backpressure, like inheritance, must be designed for.
    Observable events
    = RxView.touches(paintView);
    Flowable rows
    = db.createQuery("SELECT * …");

    View Slide

  70. Flowable vs. Observable
    Observable Flowable

    View Slide

  71. Flowable vs. Observable
    Observable Flowable
    interface Subscriber {

    void onNext(T t);

    void onComplete();

    void onError(Throwable t);

    void onSubscribe(Subscription s);

    }B
    interface Observer {

    void onNext(T t);

    void onComplete();

    void onError(Throwable t);

    void onSubscribe(Disposable d);

    }B

    View Slide

  72. Flowable vs. Observable
    Observable Flowable
    interface Subscriber {

    void onNext(T t);

    void onComplete();

    void onError(Throwable t);

    void onSubscribe(Subscription s);

    }B
    interface Observer {

    void onNext(T t);

    void onComplete();

    void onError(Throwable t);

    void onSubscribe(Disposable d);

    }B

    View Slide

  73. Flowable vs. Observable
    Observable Flowable
    interface Subscriber {

    void onNext(T t);

    void onComplete();

    void onError(Throwable t);

    void onSubscribe(Subscription s);

    }B
    interface Observer {

    void onNext(T t);

    void onComplete();

    void onError(Throwable t);

    void onSubscribe(Disposable d);

    }B

    View Slide

  74. Flowable vs. Observable
    Observable Flowable
    interface Subscriber {

    void onNext(T t);

    void onComplete();

    void onError(Throwable t);

    void onSubscribe(Subscription s);

    }B
    interface Observer {

    void onNext(T t);

    void onComplete();

    void onError(Throwable t);

    void onSubscribe(Disposable d);

    }B

    View Slide

  75. Flowable vs. Observable
    Observable Flowable
    interface Subscriber {

    void onNext(T t);

    void onComplete();

    void onError(Throwable t);

    void onSubscribe(Subscription s);

    }B
    interface Observer {

    void onNext(T t);

    void onComplete();

    void onError(Throwable t);

    void onSubscribe(Disposable d);

    }B

    View Slide

  76. Flowable vs. Observable
    Observable Flowable
    interface Subscriber {

    void onNext(T t);

    void onComplete();

    void onError(Throwable t);

    void onSubscribe(Subscription s);

    }B
    interface Observer {

    void onNext(T t);

    void onComplete();

    void onError(Throwable t);

    void onSubscribe(Disposable d);

    }B
    interface Disposable {

    void dispose();

    }B

    View Slide

  77. Flowable vs. Observable
    Observable Flowable
    interface Subscriber {

    void onNext(T t);

    void onComplete();

    void onError(Throwable t);

    void onSubscribe(Subscription s);

    }B
    interface Observer {

    void onNext(T t);

    void onComplete();

    void onError(Throwable t);

    void onSubscribe(Disposable d);

    }B
    interface Disposable {

    void dispose();

    }B
    interface Subscription {

    void cancel();

    void request(long r);

    }B

    View Slide

  78. Backpressure No Backpressure
    0…n items, complete|error Flowable Observable

    View Slide

  79. Reactive Streams
    ...is an initiative to provide a standard
    for asynchronous stream processing
    with non-blocking back pressure.

    View Slide

  80. Reactive Streams
    interface Publisher {

    void subscribe(Subscriber super T> s);

    }A

    View Slide

  81. Reactive Streams
    interface Publisher {

    void subscribe(Subscriber super T> s);

    }A
    interface Subscriber {

    void onNext(T t);

    void onComplete();

    void onError(Throwable t);

    void onSubscribe(Subscription s);

    }B

    View Slide

  82. Reactive Streams
    interface Publisher {

    void subscribe(Subscriber super T> s);

    }A
    interface Subscriber {

    void onNext(T t);

    void onComplete();

    void onError(Throwable t);

    void onSubscribe(Subscription s);

    }B
    interface Subscription {

    void request(long n);

    void cancel();

    }C

    View Slide

  83. Reactive Streams
    interface Publisher {

    void subscribe(Subscriber super T> s);

    }A
    interface Subscriber {

    void onNext(T t);

    void onComplete();

    void onError(Throwable t);

    void onSubscribe(Subscription s);

    }B
    interface Subscription {

    void request(long n);

    void cancel();

    }C
    interface Processor extends Subscriber, Publisher {

    }D


    View Slide

  84. Backpressure No Backpressure
    0…n items, complete|error Flowable Observable

    View Slide

  85. Reactive Streams
    (Backpressure)
    No Backpressure
    0…n items, complete|error Flowable Observable

    View Slide

  86. interface UserManager {
    User getUser();
    void setName(String name);
    void setAge(int age);

    }A
    Sources

    View Slide

  87. Sources
    interface UserManager {
    Observable getUser();
    void setName(String name);
    void setAge(int age);

    }A

    View Slide

  88. Source Specializations

    View Slide

  89. Source Specializations
    • Encoding subsets of Observable into the type system.

    View Slide

  90. Single
    • Either succeeds with an item or errors.
    • No backpressure support.

    View Slide

  91. Single
    • Either succeeds with an item or errors.
    • No backpressure support.
    • Think "reactive scalar".

    View Slide

  92. Completable
    • Either completes or errors. Has no items!
    • No backpressure support.

    View Slide

  93. Completable
    • Either completes or errors. Has no items!
    • No backpressure support.
    • Think "reactive runnable".

    View Slide

  94. Maybe
    • Either succeeds with an item, completes with no items, or errors.
    • No backpressure support.

    View Slide

  95. Maybe
    • Either succeeds with an item, completes with no items, or errors.
    • No backpressure support.
    • Think "reactive optional".

    View Slide

  96. Source Specializations
    • Encoding subsets of Observable into the type system.
    • Single – Item or error. Think "scalar".
    • Completable – Complete or error. Think "runnable".
    • Maybe – Item, complete, or error. Think "optional".

    View Slide

  97. Reactive Streams
    (Backpressure)
    No Backpressure
    0…n items, complete|error Flowable Observable
    item|complete|error Maybe
    item|error Single
    complete|error Completable

    View Slide

  98. Sources
    interface UserManager {
    Observable getUser();
    void setName(String name);
    void setAge(int age);

    }A

    View Slide

  99. Sources
    interface UserManager {
    Observable getUser();
    Completable setName(String name);
    Completable setAge(int age);

    }A
    void
    void


    View Slide

  100. Creating Sources

    View Slide

  101. Creating Sources
    Flowable.just("Hello");

    Flowable.just("Hello", "World");

    Observable.just("Hello");

    Observable.just("Hello", "World");

    Maybe.just("Hello");

    Single.just("Hello");

    View Slide

  102. Creating Sources
    String[] array = { "Hello", "World" };

    List list = Arrays.asList(array);

    Flowable.fromArray(array);
    Flowable.fromIterable(list);
    Observable.fromArray(array);
    Observable.fromIterable(list);

    View Slide

  103. Creating Sources
    Observable.fromCallable(new Callable() {

    @Override public String call() {Y

    return getName();

    }X

    });

    View Slide

  104. Creating Sources
    Observable.fromCallable(new Callable() {

    @Override public String call() throws Exception {Y

    return getName();Z

    }X

    });

    View Slide

  105. Creating Sources
    OkHttpClient client = // …
    Request request = // …
    Observable.fromCallable(new Callable() {

    @Override public String call() throws Exception {Y

    return client.newCall(request).execute();Z

    }X

    });


    getName()

    View Slide

  106. Creating Sources
    Flowable.fromCallable(() -> "Hello");


    Observable.fromCallable(() -> "Hello");


    Maybe.fromCallable(() -> "Hello");


    Single.fromCallable(() -> "Hello");


    Completable.fromCallable(() -> "Ignored!");

    View Slide

  107. Creating Sources
    Flowable.fromCallable(() -> "Hello");


    Observable.fromCallable(() -> "Hello");


    Maybe.fromCallable(() -> "Hello");

    Maybe.fromAction(() -> System.out.println("Hello"));

    Maybe.fromRunnable(() -> System.out.println("Hello"))


    Single.fromCallable(() -> "Hello");


    Completable.fromCallable(() -> "Ignored!");

    Completable.fromAction(() -> System.out.println("Hello"));

    Completable.fromRunnable(() -> System.out.println("Hello"));

    View Slide

  108. Creating Sources
    Observable.create();

    View Slide

  109. Creating Sources
    Observable.create(new ObservableOnSubscribe() {

    @Override

    public void subscribe(ObservableEmitter e) throws Exception {

    e.onNext("Hello");

    e.onComplete();

    }X

    });

    View Slide

  110. Creating Sources
    Observable.create(new ObservableOnSubscribe() {

    @Override

    public void subscribe(ObservableEmitter e) throws Exception {

    e.onNext("Hello");

    e.onComplete();

    }X

    });

    View Slide

  111. Creating Sources
    Observable.create(new ObservableOnSubscribe() {

    @Override

    public void subscribe(ObservableEmitter e) throws Exception {

    e.onNext("Hello");

    e.onComplete();

    }X

    });

    View Slide

  112. Creating Sources
    Observable.create(new ObservableOnSubscribe() {

    @Override

    public void subscribe(ObservableEmitter e) throws Exception {

    e.onNext("Hello");

    e.onComplete();

    }X

    });

    View Slide

  113. Creating Sources
    Observable.create(e -> {

    e.onNext("Hello");

    e.onComplete();

    });

    View Slide

  114. Creating Sources
    Observable.create(e -> {

    e.onNext("Hello");
    e.onNext("World");

    e.onComplete();

    });

    View Slide

  115. Creating Sources
    OkHttpClient client = // …
    Request request = // …
    Observable.create(e -> {
    client.newCall(request).enqueue(new Callback() {
    @Override public void onResponse(Response r) throws IOException {
    e.onNext(r.body().string());
    e.onComplete();
    }A
    @Override public void onFailure(IOException e) {
    e.onError(e);
    }B
    });

    });

    View Slide

  116. Creating Sources
    OkHttpClient client = // …
    Request request = // …
    Observable.create(e -> {
    Call call = client.newCall(request);
    call.enqueue(new Callback() {
    @Override public void onResponse(Response r) throws IOException {
    e.onNext(r.body().string());
    e.onComplete();
    }A
    @Override public void onFailure(IOException e) {
    e.onError(e);
    }B
    });

    });

    View Slide

  117. Creating Sources
    OkHttpClient client = // …
    Request request = // …
    Observable.create(e -> {
    Call call = client.newCall(request);
    e.setCancelation(() -> call.cancel());
    call.enqueue(new Callback() {
    @Override public void onResponse(Response r) throws IOException {
    e.onNext(r.body().string());
    e.onComplete();
    }A
    @Override public void onFailure(IOException e) {
    e.onError(e);
    }B
    });

    });

    View Slide

  118. Creating Sources
    OkHttpClient client = // …
    Request request = // …
    Observable.create(e -> {
    Call call = client.newCall(request);
    e.setCancelation(() -> call.cancel());
    call.enqueue(new Callback() {
    @Override public void onResponse(Response r) throws IOException {
    e.onNext(r.body().string());
    e.onComplete();
    }A
    @Override public void onFailure(IOException e) {
    e.onError(e);
    }B
    });

    });

    View Slide

  119. Creating Sources
    View view = // …
    Observable.create(e -> {
    e.setCancelation(() -> view.setOnClickListener(null));
    view.setOnClickListener(v -> e.onNext(v));

    });

    View Slide

  120. Creating Sources
    Flowable.create(e -> { … });
    Observable.create(e -> { … });
    Maybe.create(e -> { … });
    Single.create(e -> { … });
    Completable.create(e -> { … });

    View Slide

  121. Observing Sources

    View Slide

  122. Observing Sources
    Observable Flowable
    interface Subscriber {

    void onNext(T t);

    void onComplete();

    void onError(Throwable t);

    void onSubscribe(Subscription s);

    }B
    interface Observer {

    void onNext(T t);

    void onComplete();

    void onError(Throwable t);

    void onSubscribe(Disposable d);

    }B

    View Slide

  123. Observing Sources
    Observable Flowable
    interface Subscriber {

    void onNext(T t);

    void onComplete();

    void onError(Throwable t);

    void onSubscribe(Subscription s);

    }B
    interface Observer {

    void onNext(T t);A

    void onComplete();B

    void onError(Throwable t);C

    void onSubscribe(Disposable d);D

    }B
    interface Disposable {

    void dispose();

    }B
    interface Subscription {

    void cancel();

    void request(long r);

    }B

    View Slide

  124. Observing Sources
    Observable o = Observable.just("Hello");
    o.subscribe(new Observer() {

    @Override public void onNext(String s) { … }

    @Override public void onComplete() { … }

    @Override public void onError(Throwable t) { … }

    @Override public void onSubscribe(Disposable d) {
    ???
    }B

    });
    Flowable
    interface Subscriber {

    void onNext(T t);

    void onComplete();

    void onError(Throwable t);

    void onSubscribe(Subscription s);

    }B
    interface Disposable {

    void dispose();

    }B
    interface Subscription {

    void cancel();

    void request(long r);

    }B
    interface T

    T t ;A

    ;B

    ;C

    ;D


    View Slide

  125. Observing Sources
    Observable o = Observable.just("Hello");
    o.subscribe(new DisposableObserver() {

    @Override public void onNext(String s) { … }

    @Override public void onComplete() { … }

    @Override public void onError(Throwable t) { … }

    });




    @Override public void onSubscribe(Disposable d) {
    ???
    }B


    View Slide

  126. Observing Sources
    Observable o = Observable.just("Hello");
    o.subscribe(new DisposableObserver() {

    @Override public void onNext(String s) { … }

    @Override public void onComplete() { … }

    @Override public void onError(Throwable t) { … }

    });Z
    // TODO how do we dispose???

    View Slide

  127. Observing Sources
    Observable o = Observable.just("Hello");
    DisposableObserver observer = new DisposableObserver() {

    @Override public void onNext(String s) { … }

    @Override public void onComplete() { … }

    @Override public void onError(Throwable t) { … }

    }
    o.subscribe(observer);Z
    // TODO how do we dispose??????

    View Slide

  128. Observing Sources
    Observable o = Observable.just("Hello");
    DisposableObserver observer = new DisposableObserver() {

    @Override public void onNext(String s) { … }

    @Override public void onComplete() { … }

    @Override public void onError(Throwable t) { … }

    }
    o.subscribe(observer);Z
    observer.dispose();

    View Slide

  129. Observing Sources
    Observable o = Observable.just("Hello");
    o.subscribe(new DisposableObserver() {

    @Override public void onNext(String s) { … }

    @Override public void onComplete() { … }

    @Override public void onError(Throwable t) { … }

    });Z

    View Slide

  130. Observing Sources
    Observable o = Observable.just("Hello");
    o.subscribeWith(new DisposableObserver() {

    @Override public void onNext(String s) { … }

    @Override public void onComplete() { … }

    @Override public void onError(Throwable t) { … }

    });Z

    View Slide

  131. Observing Sources
    Observable o = Observable.just("Hello");
    Disposable d = o.subscribeWith(new DisposableObserver() {

    @Override public void onNext(String s) { … }

    @Override public void onComplete() { … }

    @Override public void onError(Throwable t) { … }

    });Z
    d.dispose();

    View Slide

  132. Observing Sources
    Observable o = Observable.just("Hello");
    CompositeDisposable disposables = new CompositeDisposable();
    disposables.add(o.subscribeWith(new DisposableObserver() {

    @Override public void onNext(String s) { … }

    @Override public void onComplete() { … }

    @Override public void onError(Throwable t) { … }

    }));Z
    disposables.dispose();




    d.dispose();
    Disposable d =

    View Slide

  133. Observing Sources
    Observable o = Observable.just("Hello");
    o.subscribeWith(new DisposableObserver() { … });Z
    Maybe m = Maybe.just("Hello");
    m.subscribeWith(new DisposableMaybeObserver() { … });Z
    Single s = Single.just("Hello");
    s.subscribeWith(new DisposableSingleObserver() { … });Z
    Completable c = Completable.completed();
    c.subscribeWith(new DisposableCompletableObserver() { … });Z
    disposables.add(

    @Override public void onNext(String s) { … }

    @Override public void onComplete() { … }

    @Override public void onError(Throwable t) { … }

    )
    disposables.dispose();

    View Slide

  134. Observing Sources
    Flowable f = Flowable.just("Hello");
    f.subscribeWith(new DisposableSubscriber() { … });
    Observable o = Observable.just("Hello");
    o.subscribeWith(new DisposableObserver() { … });
    Maybe m = Maybe.just("Hello");
    m.subscribeWith(new DisposableMaybeObserver() { … });
    Single s = Single.just("Hello");
    s.subscribeWith(new DisposableSingleObserver() { … });
    Completable c = Completable.completed();
    c.subscribeWith(new DisposableCompletableObserver() { … });

    View Slide

  135. Observing Sources
    Flowable f = Flowable.just("Hello");
    f.subscribeWith(new DisposableSubscriber() { … });
    Observable o = Observable.just("Hello");
    o.subscribeWith(new DisposableObserver() { … });
    Maybe m = Maybe.just("Hello");
    m.subscribeWith(new DisposableMaybeObserver() { … });
    Single s = Single.just("Hello");
    s.subscribeWith(new DisposableSingleObserver() { … });
    Completable c = Completable.completed();
    c.subscribeWith(new DisposableCompletableObserver() { … });

    View Slide

  136. Observing Sources
    Flowable f = Flowable.just("Hello");
    Disposable d1 = f.subscribeWith(new DisposableSubscriber() { … });
    Observable o = Observable.just("Hello");
    Disposable d2 = o.subscribeWith(new DisposableObserver() { … });
    Maybe m = Maybe.just("Hello");
    Disposable d3 = m.subscribeWith(new DisposableMaybeObserver() { … });
    Single s = Single.just("Hello");
    Disposable d4 = s.subscribeWith(new DisposableSingleObserver() { … });
    Completable c = Completable.completed();
    Disposable d5 = c.subscribeWith(new DisposableCompletableObserver() { … });

    View Slide

  137. RxJava
    • A set of classes for representing sources of data.
    • A set of classes for listening to data sources.
    • A set of methods for modifying and composing data.

    View Slide

  138. RxJava
    • A set of classes for representing sources of data.
    • A set of classes for listening to data sources.
    • A set of methods for modifying and composing data.

    View Slide

  139. Operators

    View Slide

  140. Operators
    • Manipulate or combine data in some way.

    View Slide

  141. Operators
    • Manipulate or combine data in some way.
    • Manipulate threading in some way.

    View Slide

  142. Operators
    • Manipulate or combine data in some way.
    • Manipulate threading in some way.
    • Manipulate emissions in some way.

    View Slide

  143. Operators
    String greeting = "Hello";

    View Slide

  144. Operators
    String greeting = "Hello";Z
    String yelling = greeting.toUppercase();

    View Slide

  145. Operators
    Observable greeting = Observable.just("Hello");Z
    String yelling = greeting.toUppercase();Y

    View Slide

  146. Operators
    Observable greeting = Observable.just("Hello");
    Observable yelling = greeting.map(s -> s.toUppercase());Y

    View Slide

  147. Operators
    Observable greeting = Observable.just("Hello");
    Observable yelling = greeting.map(s -> s.toUppercase());Y

    View Slide

  148. Operators
    @Override public void success() {
    runOnUiThread(new Runnable() {
    @Override public void run() {
    tv.setText(um.getUser().toString());
    }4
    });
    }A

    View Slide

  149. Operators
    Observable user = um.getUser();

    View Slide

  150. Operators
    Observable user = um.getUser();
    Observable mainThreadUser =
    user.observeOn(AndroidSchedulers.mainThread());

    View Slide

  151. Operators
    Observable user = um.getUser();
    Observable mainThreadUser =
    user.observeOn(AndroidSchedulers.mainThread());

    View Slide

  152. Operators
    OkHttpClient client = // …
    Request request = // …
    Response response = client.newCall(request).execute();

    View Slide

  153. Operators
    OkHttpClient client = // …
    Request request = // …
    Observable response = Observable.fromCallable(() -> {
    return client.newCall(request).execute();
    });

    View Slide

  154. Operators
    OkHttpClient client = // …
    Request request = // …
    Observable response = Observable.fromCallable(() -> {
    return client.newCall(request).execute();
    });
    Observable backgroundResponse =
    response.subscribeOn(Schedulers.io());

    View Slide

  155. Operators
    OkHttpClient client = // …
    Request request = // …
    Observable response = Observable.fromCallable(() -> {
    return client.newCall(request).execute();
    });
    Observable backgroundResponse =
    response.subscribeOn(Schedulers.io());

    View Slide

  156. Operators
    OkHttpClient client = // …
    Request request = // …
    Observable response = Observable.fromCallable(() -> {
    return client.newCall(request).execute();
    });
    Observable backgroundResponse =
    response.subscribeOn(Schedulers.io());

    View Slide

  157. Operators
    OkHttpClient client = // …
    Request request = // …
    Observable response = Observable.fromCallable(() -> {
    return client.newCall(request).execute();
    })
    .subscribeOn(Schedulers.io());Y

    View Slide

  158. Operators
    OkHttpClient client = // …
    Request request = // …
    Observable response = Observable.fromCallable(() -> {
    return client.newCall(request).execute();
    })
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread());Y

    View Slide

  159. Operators
    OkHttpClient client = // …
    Request request = // …
    Observable response = Observable.fromCallable(() -> {
    return client.newCall(request).execute();
    })
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .map(response -> response.body().string());Y

    View Slide

  160. Operators
    OkHttpClient client = // …
    Request request = // …
    Observable response = Observable.fromCallable(() -> {
    return client.newCall(request).execute();
    })
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .map(response -> response.body().string());Y// NetworkOnMainThread!

    View Slide

  161. Operators
    OkHttpClient client = // …
    Request request = // …
    Observable response = Observable.fromCallable(() -> {
    return client.newCall(request).execute();
    })
    .subscribeOn(Schedulers.io())
    .map(response -> response.body().string()) // Ok!
    .observeOn(AndroidSchedulers.mainThread());Y// NetworkOnMainThread!

    View Slide

  162. Operator Specialization

    View Slide

  163. Operator Specialization
    Observable

    View Slide

  164. Operator Specialization
    first()
    Observable

    View Slide

  165. Operator Specialization
    first()
    Observable
    Observable

    View Slide

  166. Operator Specialization
    1 2 3 4 5 6 7 8 9 10 11
    first()
    1
    Observable
    Observable

    View Slide

  167. Operator Specialization
    1 2 3 4 5 6 7 8 9 10 11
    get(0)
    1
    List
    List

    View Slide

  168. Operator Specialization
    first()
    Observable
    Observable

    View Slide

  169. Operator Specialization
    first()
    Observable
    Single

    View Slide

  170. Operator Specialization
    1 2 3 4 5 6 7 8 9 10 11
    first()
    1
    Observable
    Single

    View Slide

  171. Operator Specialization
    first()
    Observable
    Single

    View Slide

  172. Operator Specialization
    first()
    Observable
    Single
    NoSuchElementException

    View Slide

  173. Operator Specialization
    first()
    Observable

    View Slide

  174. Operator Specialization
    firstElement()
    Observable

    View Slide

  175. Operator Specialization
    firstElement()
    Observable
    Maybe

    View Slide

  176. Operator Specialization
    firstElement()
    Observable
    Maybe

    View Slide

  177. Operator Specialization
    ignoreElements()
    Observable

    View Slide

  178. Operator Specialization
    ignoreElements()
    Observable
    Completable

    View Slide

  179. Operator Specialization
    1 2 3 4 5 6 7 8 9
    ignoreElements()
    Observable
    Completable

    View Slide

  180. Operator Specialization
    ignoreElements()
    Flowable
    Completable

    View Slide

  181. Operator Specialization
    firstElement()
    Flowable
    Maybe

    View Slide

  182. Operator Specialization
    first()
    Flowable
    Single

    View Slide

  183. Flowable Observable Maybe Single Completable
    Flowable toObservable()
    reduce()
    elementAt()
    firstElement()
    lastElement()
    singleElement()
    scan()
    elementAt()
    first()/firstOrError()
    last()/lastOrError()
    single/singleOrError()
    all()/any()/count()
    (and more)
    ignoreElements()
    Observable toFlowable()
    reduce()
    elementAt()
    firstElement()
    lastElement()
    singleElement()
    scan()
    elementAt()
    first()/firstOrError()
    last()/lastOrError()
    single/singleOrError()
    all()/any()/count()
    (and more)
    ignoreElements()
    Maybe toFlowable() toObservable()
    toSingle()
    sequenceEqual()
    toCompletable()
    Single toFlowable() toObservable() toMaybe() toCompletable()
    Completable toFlowable() toObservable() toMaybe()
    toSingle()
    toSingleDefault()
    From
    To

    View Slide

  184. Flowable Observable Maybe Single Completable
    Flowable toObservable()
    reduce()
    elementAt()
    firstElement()
    lastElement()
    singleElement()
    scan()
    elementAt()
    first()/firstOrError()
    last()/lastOrError()
    single/singleOrError()
    all()/any()/count()
    (and more)
    ignoreElements()
    Observable toFlowable()
    reduce()
    elementAt()
    firstElement()
    lastElement()
    singleElement()
    scan()
    elementAt()
    first()/firstOrError()
    last()/lastOrError()
    single/singleOrError()
    all()/any()/count()
    (and more)
    ignoreElements()
    Maybe toFlowable() toObservable()
    toSingle()
    sequenceEqual()
    toCompletable()
    Single toFlowable() toObservable() toMaybe() toCompletable()
    Completable toFlowable() toObservable() toMaybe()
    toSingle()
    toSingleDefault()
    From
    To

    View Slide

  185. Flowable Observable Maybe Single Completable
    Flowable toObservable()
    reduce()
    elementAt()
    firstElement()
    lastElement()
    singleElement()
    scan()
    elementAt()
    first()/firstOrError()
    last()/lastOrError()
    single/singleOrError()
    all()/any()/count()
    (and more)
    ignoreElements()
    Observable toFlowable()
    reduce()
    elementAt()
    firstElement()
    lastElement()
    singleElement()
    scan()
    elementAt()
    first()/firstOrError()
    last()/lastOrError()
    single/singleOrError()
    all()/any()/count()
    (and more)
    ignoreElements()
    Maybe toFlowable() toObservable()
    toSingle()
    sequenceEqual()
    toCompletable()
    Single toFlowable() toObservable() toMaybe() toCompletable()
    Completable toFlowable() toObservable() toMaybe()
    toSingle()
    toSingleDefault()
    From
    To

    View Slide

  186. Being Reactive

    View Slide

  187. Being Reactive
    um.getUser()

    View Slide

  188. Being Reactive
    um.getUser()
    .observeOn(AndroidSchedulers.mainThread())

    View Slide

  189. Being Reactive
    um.getUser()
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeWith(new DisposableObserver() {
    @Override public void onNext(User user) {
    }1
    @Override public void onComplete() { /* ignored */ }
    @Override public void onError(Throwable t) { /* crash or show */ }
    });

    View Slide

  190. Being Reactive
    um.getUser()
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeWith(new DisposableObserver() {
    @Override public void onNext(User user) {
    tv.setText(user.toString());
    }1
    @Override public void onComplete() { /* ignored */ }
    @Override public void onError(Throwable t) { /* crash or show */ }
    });2

    View Slide

  191. Being Reactive
    disposables.add(um.getUser()
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeWith(new DisposableObserver() {
    @Override public void onNext(User user) {
    tv.setText(user.toString());
    }1
    @Override public void onComplete() { /* ignored */ }
    @Override public void onError(Throwable t) { /* crash or show */ }
    }));2

    View Slide

  192. Being Reactive
    // onCreate
    disposables.add(um.getUser()
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeWith(new DisposableObserver() {
    @Override public void onNext(User user) {
    tv.setText(user.toString());
    }1
    @Override public void onComplete() { /* ignored */ }
    @Override public void onError(Throwable t) { /* crash or show */ }
    }));
    // onDestroy
    disposables.dispose();

    View Slide

  193. Being Reactive
    um.setName("Jane Doe")

    View Slide

  194. Being Reactive
    um.setName("Jane Doe")
    .subscribeOn(Schedulers.io())

    View Slide

  195. Being Reactive
    um.setName("Jane Doe")
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())

    View Slide

  196. Being Reactive
    um.setName("Jane Doe")
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeWith(new DisposableCompletableObserver() {
    @Override public void onComplete() {
    }1
    @Override public void onError(Throwable t) {
    // retry or show
    }2
    });

    View Slide

  197. Being Reactive
    um.setName("Jane Doe")
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeWith(new DisposableCompletableObserver() {
    @Override public void onComplete() {
    // success! re-enable editing
    }1
    @Override public void onError(Throwable t) {
    // retry or show
    }2
    });3

    View Slide

  198. Being Reactive
    disposables.add(um.setName("Jane Doe")
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeWith(new DisposableCompletableObserver() {
    @Override public void onComplete() {
    // success! re-enable editing
    }1
    @Override public void onError(Throwable t) {
    // retry or show
    }2
    }));3

    View Slide

  199. Architecture

    View Slide

  200. Architecture
    • Less allocation to create a stream.
    • Less overhead when subscribing to a stream.

    View Slide

  201. RxJava 2

    View Slide

  202. RxJava 2
    • Build an app that reacts properly instead of copes desperately!

    View Slide

  203. RxJava 2
    • Build an app that reacts properly instead of copes desperately!
    • Final release scheduled for 2016-10-29.

    View Slide

  204. Living with 1.x and 2.x
    class RxJavaInterop {

    static Flowable toV2Flowable(rx.Observable o) { … }

    static Observable toV2Observable(rx.Observable o) { … }
    static Maybe toV2Maybe(rx.Single s) { … }
    static Maybe toV2Maybe(rx.Completable c) { … }

    static Single toV2Single(rx.Single s) { … }

    static Completable toV2Completable(rx.Completable c) { … }

    static rx.Observable toV1Observable(Publisher p) { … }
    static rx.Observable toV1Observable(Observable o, …) { … }

    static rx.Single toV1Single(Single o) { … }
    static rx.Single toV1Single(Maybe m) { … }

    static rx.Completable toV1Completable(Completable c) { … }
    static rx.Completable toV1Completable(Maybe m) { … }

    }X

    View Slide

  205. Living with 1.x and 2.x
    class RxJavaInterop {

    static Flowable toV2Flowable(rx.Observable o) { … }

    static Observable toV2Observable(rx.Observable o) { … }
    static Maybe toV2Maybe(rx.Single s) { … }
    static Maybe toV2Maybe(rx.Completable c) { … }

    static Single toV2Single(rx.Single s) { … }

    static Completable toV2Completable(rx.Completable c) { … }

    static rx.Observable toV1Observable(Publisher p) { … }
    static rx.Observable toV1Observable(Observable o, …) { … }

    static rx.Single toV1Single(Single o) { … }
    github.com/akarnokd/RxJava2Interop

    View Slide

  206. dependencies {

    compile 'io.reactivex.rxjava2:rxjava:2.0.0-RC3'

    compile 'io.reactivex.rxjava2:rxandroid:2.0.0-RC1'
    // Optionally...

    compile 'com.github.akarnokd:rxjava2-interop:0.3.0'
    }

    View Slide

  207. jakewharton
    jakewharton
    jakewharton
    twitter.com/
    google.com/+
    .com
    Exploring RxJava

    View Slide