将Completable转换为Single的规范方法? [英] Canonical way to convert Completable to Single?

查看:188
本文介绍了将Completable转换为Single的规范方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要执行的RxJava Completable,然后链接到Single<Long>.我可以这样写:

return Completable.complete().toSingleDefault(0L).flatMap { Single.just(1L) }

但这似乎不必要地复杂.我本以为Completable#toSingle()可以完成这项工作,但是如果我写:

Completable.complete().toSingle { Single.just(1L) }

我得到了错误. Completable中是否缺少功能?还是我忽略了某些内容?

解决方案

您可能想使用 andThen 操作符,它将在Completable完成后订阅您发送给它的源.

return Completable.complete()
    .andThen(Single.just(1L))

就像@akarnokd所说的,这是非依赖性延续的情况. /p>

如果您的源需要在运行时解析,则这将是依赖于延期的延续,则需要defer它:

return Completable.complete()
    .andThen(Single.defer(() -> Single.just(1L)))

I have an RxJava Completable that I want to execute, then chain to a Single<Long>. I can write it like this:

return Completable.complete().toSingleDefault(0L).flatMap { Single.just(1L) }

but this seems unnecessarily complicated. I would have thought Completable#toSingle() would do the job, but if I write:

Completable.complete().toSingle { Single.just(1L) }

I get errors. Is there a missing function in Completable or am I overlooking something?

解决方案

You probably want to use the andThen opeator, which will subscribe to the source you send to it after the Completable completes.

return Completable.complete()
    .andThen(Single.just(1L))

As @akarnokd said, this is a case of non-dependent continuations.

In case of your source needing to be resolved at runtime, this would be a deferred-dependent continuation, and you'd need to defer it:

return Completable.complete()
    .andThen(Single.defer(() -> Single.just(1L)))

这篇关于将Completable转换为Single的规范方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆