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
What's the difference between rxjava2's Maybe and Optional?
提问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 Maybe
can do and Optional
cannot (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
Maybe
is a wrapper around an operation/eventthat may have either
Maybe
是一个操作/事件的包装器,它可能有
- A single result
- No result
- Error result
- 一个结果
- 没有结果
- 错误结果
However Optional is a wrapper around a valuethat may either be
然而 Optional 是一个值的包装器,它可能是
- Present
- Absent
- 展示
- 缺席的
In your example, in the map
operation, the computation is synchronous (i.e. 6/i
is 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 Optional
makes 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
Maybe
will 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
flatMap
instead ofmap
. I will then not have to use any ofOptional
orMaybe
..flatMap(i -> { try { int result = 6 / i; return Observable.just(result); } catch (Exception e) { return Observable.empty(); } })
- 如果你想传播为什么除法是不可能的,那么你会想要报告发生的异常。在这种情况下,使用
Maybe
会更有意义。 如果您对空值和错误原因都不感兴趣,那么您只想跳过传播这些结果。在这种情况下,我会使用 a
flatMap
而不是map
. 然后我将不必使用任何Optional
或Maybe
。.flatMap(i -> { try { int result = 6 / i; return Observable.just(result); } catch (Exception e) { return Observable.empty(); } })
Maybe
is also useful when you have an Observable
that 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
Maybe
is a lazy stream of zero or one things (and being a stream can result in an error). Optional
is not lazy, it it is either present or absent. There is no sense of deferred calculation with an Optional
whereas there is with Maybe
.
Maybe
是零或一件事的惰性流(并且作为流可能会导致错误)。Optional
不是懒惰,它要么存在,要么不存在。使用 an 没有延迟计算的感觉,Optional
而使用Maybe
.
回答by m.ostroverkhov
The difference relevant to your question is that Maybe
can propagate error while Optional
cannot - in your example one cannot distinguish between error and empty result. If error handling is important, Optional
is useless, while Maybe
has Maybe.error(Throwable)
. API-wise, for your use case I would prefer Single
to 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明智的,为您的使用情况下,我宁愿Single
来Maybe
-因为它产生任何错误或单个结果,所以返回类型是Observable<Single<T>>
回答by Matthias247
RxJava 2 targets Java 6. This means there is no builtin Optional
support guaranteed, and they have to bring their own. Similar to how they have to bring their own Function
types.
RxJava 2 面向 Java 6。这意味着不能Optional
保证内置支持,他们必须自带支持。类似于他们如何携带自己的Function
类型。
If your application/library only supports Java >= 8 you can use whatever suits you better.
如果您的应用程序/库仅支持 Java >= 8,您可以使用更适合您的任何东西。