What is the difference between rxjava2 Maybe and Optional?

Doc says

Conceptually, this combination of Single and Completable, which means capturing a radiation circuit, where there may be 0 or 1 element or an error signaled by some reactive source.

But I'm not sure what that really means. It seems to be java8 Optional.

The following two codes have the same result, but I don’t know what can do Maybe, but Optionalcannot (or cumbersome).

  @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 upgrade to Observable<Maybe<T>>?

+9
source share
4 answers

Maybe /,

- ,

  • Present

, map, (.. 6/i ), ( ) ( ). , Optional .

:

  • , , . Maybe .
  • , , . flatMap map. - Optional Maybe.

    .flatMap(i -> { 
      try { 
        int result = 6 / i; 
        return Observable.just(result); 
      } catch (Exception e) { 
        return Observable.empty(); 
      } 
    }) 
    

Maybe , Observable, , , , , , , firstElement() Observable. Maybe, , ( Observable ), ( - ).

+19

Maybe - ( ). Optional , , . Optional, Maybe.

+9

, , , Maybe , Optional - . , Optional , Maybe Maybe.error(Throwable). API-, Single - Maybe - , , Observable<Single<T>>

+4

RxJava 2 Java 6. , Optional , . , Function.

If your application / library only supports Java> = 8, then you can use whatever suits you best.

+1
source

Source: https://habr.com/ru/post/1659928/


All Articles