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) }

但这似乎不必要地复杂.我本以为Completable#toSingle()人就能胜任,但如果我写:

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

我会犯错误.Completable中是否缺少功能,或者我忽略了什么?

推荐答案

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

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

正如@akarnokd所说,这是一个non-dependent continuations人的 case .

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)))

Kotlin相关问答推荐

带有Spring Boot和Kotline的可嵌入实体

为什么Kotlin协程程序即使有延迟也能输出?

在 Kotlin 中将 Array 转换为 IntArray 时丢失值

为什么使用 return instance ?: synchronized(this) { instance ?: PreferenceParameterState(context) } 时无法获得单例?

为什么Kotlin不用static inner class来实现带有object关键字的单例呢?

协程子作业(job)取消

Kotlin:调用 CoroutineScope.launch 与在协程内启动之间的区别

如何访问嵌套在另一个 map 中的 map 中的值(在 kotlin 中)

Kotlin Path.useLines { } - 如何不获取 IOException("Stream closed")?

使用 Discord4j 交叉发布 Discord 消息

Kotlin 从其他类调用成员扩展函数

Kotlin 无法找到或加载主类

Kotlin:泛型、反射以及类型 T 和 T:Any 之间的区别

Android Room - error: Cannot figure out how to save this field into database

Kotlin:sealed class cannot "contain" data classes?

添加抽象的私有getter和公共setter的正确方法是什么?

TornadoFX 中设置 PrimaryStage 或 Scene 属性的方法

如何在Kotlin中使方法param可变?

目前不支持 Gradle 项目的自动库版本更新.请手动更新您的 build.gradle

Kotlin:访问 when 语句的参数