java rxjava2的Maybe和Optional有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40439579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 05:12:52  来源:igfitidea点击:

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

javarx-javaoptionalrx-java2

提问by smallufo

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.

从概念上讲,它是 Single 和 Completable 的结合,提供了捕获可能有 0 或 1 个项目或某个反应源发出错误信号的发射模式的方法。

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

但我不确定它的真正含义。似乎是 java8 的Optional.

The following two codes have the same result , but I don't know what Maybecan do and Optionalcannot (or cumbersome) do.

下面两个代码有相同的结果,但我不知道什么Maybe可以做什么Optional不能(或繁琐)做什么。

  @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>>?

在 rxJava1 中,我的 API 曾经返回Observable<Optional<T>>,这是一种难闻的气味吗?我应该改为Observable<Maybe<T>>?

回答by Praveer Gupta

Maybeis a wrapper around an operation/eventthat may have either

Maybe是一个操作/事件的包装器,它可能有

  1. A single result
  2. No result
  3. Error result
  1. 一个结果
  2. 没有结果
  3. 错误结果

However Optional is a wrapper around a valuethat may either be

然而 Optional 是一个的包装器,它可能是

  1. Present
  2. Absent
  1. 展示
  2. 缺席的

In your example, in the mapoperation, the computation is synchronous (i.e. 6/iis synchronous and can result in a value immediately) and you want to propagate a value (if division is possible) or empty value (if division is not possible). Hence using Optionalmakes more sense.

在您的示例中,在map操作中,计算是同步的(即6/i同步并且可以立即产生一个值)并且您想要传播一个值(如果可以进行除法)或空值(如果无法进行除法)。因此使用Optional更有意义。

There are however other options also:

然而,还有其他选择:

  • If you want to propagate why division is not possible then you would want to report the exception that occurred. In such a case using Maybewill make more sense.
  • If you are not interested in both empty value and reason of error, then you simply want to skip propagating those results. In such a scenario I would use a flatMapinstead of map. I will then not have to use any of Optionalor Maybe.

    .flatMap(i -> { 
      try { 
        int result = 6 / i; 
        return Observable.just(result); 
      } catch (Exception e) { 
        return Observable.empty(); 
      } 
    }) 
    
  • 如果你想传播为什么除法是不可能的,那么你会想要报告发生的异常。在这种情况下,使用Maybe会更有意义。
  • 如果您对空值和错误原因都不感兴趣,那么您只想跳过传播这些结果。在这种情况下,我会使用 aflatMap而不是map. 然后我将不必使用任何OptionalMaybe

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

Maybeis also useful when you have an Observablethat can emit multiple values but you are interested in, let's say, only the first one and hence you use the firstElement()operator on the Observable. This returns a Maybe because either there is a single value, or there is no value (if source Observable does not emit any value before completing) or there is an error (if source Observable errors before emitting any value).

Maybe当你有一个Observable可以发出多个值但你感兴趣的时候也很有用,比如说,只有第一个,因此你firstElement()在 Observable 上使用运算符。这将返回一个 Maybe ,因为要么有一个值,要么没有值(如果源 Observable 在完成之前没有发出任何值)或者有一个错误(如果源 Observable 在发出任何值之前出错)。

回答by Dave Moten

Maybeis a lazy stream of zero or one things (and being a stream can result in an error). Optionalis not lazy, it it is either present or absent. There is no sense of deferred calculation with an Optionalwhereas there is with Maybe.

Maybe是零或一件事的惰性流(并且作为流可能会导致错误)。Optional不是懒惰,它要么存在,要么不存在。使用 an 没有延迟计算的感觉,Optional而使用Maybe.

回答by m.ostroverkhov

The difference relevant to your question is that Maybecan propagate error while Optionalcannot - in your example one cannot distinguish between error and empty result. If error handling is important, Optionalis useless, while Maybehas Maybe.error(Throwable). API-wise, for your use case I would prefer Singleto Maybe- because it yields either Error or single Result, so return type would be Observable<Single<T>>

与您的问题相关的区别在于Maybe可以传播错误而不能传播错误Optional- 在您的示例中,无法区分错误和空结果。如果错误处理很重要,Optional则无用,而Maybe具有Maybe.error(Throwable). API明智的,为您的使用情况下,我宁愿SingleMaybe-因为它产生任何错误或单个结果,所以返回类型是Observable<Single<T>>

回答by Matthias247

RxJava 2 targets Java 6. This means there is no builtin Optionalsupport guaranteed, and they have to bring their own. Similar to how they have to bring their own Functiontypes.

RxJava 2 面向 Java 6。这意味着不能Optional保证内置支持,他们必须自带支持。类似于他们如何携带自己的Function类型。

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

如果您的应用程序/库仅支持 Java >= 8,您可以使用更适合您的任何东西。