【问题标题】:RxJava Completabe andThen testingRxJava Completabe 然后测试
【发布时间】:2017-08-14 17:55:08
【问题描述】:

我有以下 RxJava2 Kotlin 代码:

val tester = Completable.complete()
            .andThen(SingleSource<Int> { Single.just(42) })
            .test()        
tester.assertComplete()
tester.assertValue(42)

这模拟了一个 Completable observable(想象一个简单的 API 更新操作)和一个 Single observable(想象一个 API 上的 get 操作)。我想以这样的方式连接两个可观察对象,当 Completable 完成时,Single 运行,最后我在观察者(Int 42)上获得 onSuccess 事件。

但是,此测试代码不起作用。断言失败并出现以下错误:

java.lang.AssertionError: Not completed
(latch = 1, values = 0, errors = 0, completions = 0))

我无法理解我做错了什么,我希望 Completable 在订阅时发出 onComplete,然后 Single 订阅,并且我的观察者 (tester) 得到一个值为 42 的 onSuccess 事件,但似乎订阅保持“暂停”状态,不发出任何内容。

这个想法与这篇博文中的想法相似:https://android.jlelse.eu/making-your-rxjava-intentions-clearer-with-single-and-completable-f064d98d53a8

apiClient.updateMyData(myUpdatedData) // a Completable
    .andThen(performOtherOperation()) // a Single<OtherResult>
    .subscribe(otherResult -> {
        // handle otherResult
    }, throwable -> {
        // handle error
    });

【问题讨论】:

    标签: rx-java


    【解决方案1】:

    问题在于 Kotlin 对花括号的使用模棱两可:

    .andThen(SingleSource<Int> { Single.just(42) })
    

    您创建了一个 SingleSource 并注意到它的 SingleObserver,但它被 Kotlin 语法隐藏了。你需要的是简单的使用:

    .andThen(Single.just(42))
    

    或延迟使用

    .andThen(Single.defer { Single.just(42) })
    

    【讨论】:

    • 感谢 akarnokd,出于某种原因,我将其添加到代码中,因为最初我正在执行 .andThen { Single.just(42) },但未编译。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多