What's the difference between rxjava2's Maybe and Optional?

557 views
Skip to first unread message

smallufo

unread,
Nov 5, 2016, 10:57:26 AM11/5/16
to rxj...@googlegroups.com

The doc says Conceptually, it is a union of Single and Completable providing the means to capture an emission pattern where there could be 0 or 1 item or an error signalled by some reactive source.

But I am not sure what it truly means. It seems it is java8's Optional.

The following two codes have the same result , but I don't know what Maybe can do and Optional cannot (or cumbersome) do.


@Test
  public void testMaybe1() {
    Observable.just(3, 2, 1, 0, -1)
      .map(i -> {
        try {
          int result = 6 / i;
          return Maybe.just(result);
        } catch (Exception e) {
          return Maybe.empty();
        }
      })
      .blockingForEach(maybe -> {
          logger.info("result = {}", maybe.blockingGet());
        }
      );
  }


  @Test
  public void testMaybe2() {
    Observable.just(3, 2, 1, 0, -1)
      .map(i -> {
        try {
          int result = 6 / i;
          return Optional.of(result);
        } catch (Exception e) {
          return Optional.empty();
        }
      })
      .blockingForEach(opt -> {
          logger.info("result = {}", opt.orElse(null));
        }
      );
  }

The results are the same :

result = 2
result = 3
result = 6
result = null
result = -6

In rxJava1 , My API used to return Observable<Optional<T>> , Is it a bad smell ? Should I change to Observable<Maybe<T>> ?


Jake Wharton

unread,
Nov 5, 2016, 1:08:47 PM11/5/16
to smallufo, rxj...@googlegroups.com

Maybe is lazy, Optional is eager. It's similar to Single vs a scalar (like String). The formers are computed lazily on subscribe and the latters are computed eagerly before returned.

Reply all
Reply to author
Forward
0 new messages