java 有没有像 Single.empty() 这样的东西
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40606231/
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
Is there something like Single.empty()
提问by Fred
I'm in the process of migrating from Rx 1 to Rx 2 and suddenly while reading through posts I found out that Singleshould be the type of observable to use for retrofit calls.
我正在从 Rx 1 迁移到 Rx 2 的过程中,突然在阅读帖子时我发现Single应该是用于改造调用的可观察类型。
So I've decided to give it a shot and while migrating our retrofit calls to Rx 2 I also changed the return value to Single<whatever>.
所以我决定试一试,在将我们的改造调用迁移到 Rx 2 时,我还将返回值更改为Single<whatever>.
Now the issue is, some of our tests mock the network services something similar to:
现在的问题是,我们的一些测试模拟了类似于以下内容的网络服务:
when(userService.logout()).thenReturn(Observable.empty())
As you can see prior to migrating the calls we used to simply complete the stream by telling the userServicemock to return an empty observable.
正如您在迁移调用之前所看到的,我们过去常常通过告诉userService模拟返回一个空的可观察对象来简单地完成流。
While migrating to the Single"version" of the calls we no longer can use Observable.empty()because the call doesn't return an Observable, but returns a Single.
在迁移到Single调用的“版本”时,我们不再可以使用,Observable.empty()因为调用不返回Observable,而是返回Single。
I've ended up doing something like:
我最终做了类似的事情:
when(userService.logout()).thenReturn(
Single.fromObservable(Observable.<whatever>empty()))
My questions are:
我的问题是:
- Is there a better way of doing this?
- Am I missing anything important that I should know - something like this actually doesn't behave as I'm expecting it to.
- 有没有更好的方法来做到这一点?
- 我是否遗漏了任何我应该知道的重要信息 - 像这样的事情实际上并不像我期望的那样表现。
回答by akarnokd
Single.empty()makes no sense because Singlehas to have a single item or an error. You could just have kept Observableor switched to Maybewhich does allow empty or Completablewhich doesn't emit an item at all.
Single.empty()没有意义,因为Single必须有单个项目或错误。您可以只保留Observable或切换到Maybe允许空的或Completable根本不发出项目的。
回答by Florian Wolf
A workaround e.g. for tests would be
例如测试的解决方法是
Observable.<Whatever>empty().toSingle()
Observable.<Whatever>empty().toSingle()
keep in mind that this does not call the subscribers at all.
请记住,这根本不会调用订阅者。

