【问题标题】:Why does thread changed to Main thread in callback?为什么线程在回调中改为主线程?
【发布时间】:2020-02-11 15:50:26
【问题描述】:

我正在使用 Kotlin 和 RxJava 开发一个 android 应用程序。

我使用 android 最新 API 开发了应用内结算。

但是这个库只支持异步回调。

所以我写了这样的代码:

private fun consumePlayStore(consumeParams: ConsumeParams, secKey: String, purchase: Purchase): Single<Pair<String, Purchase>> {
    return Single.create<Pair<String, Purchase>> { emitter ->
        Log.d("TEST", "[Billing] consumePlayStore") // IO Thread

        // Google InApp Library call
        playStoreBillingClient?.consumeAsync(consumeParams) { result, _ ->

            // In here, thread is Main!!! Why!!!
            Log.d("TEST", "[Billing] consumePlayStore - response")  // Main Thread
        }
    }
}


fun consume() {

    verifyCompletable.andThen(consumePlayStore())
            .flatMap(otherJob)
            .subscribeOn(ioScheduler)
            .observeOn(uiScheduler)
            .subscribe()


}

不知道为什么在回调中改线程?

谁能告诉我为什么?

我该如何解决这个问题???

或者更好的设计???

【问题讨论】:

    标签: android kotlin rx-java


    【解决方案1】:

    我找到了原因和解决办法。

    首先,原因是Google InApp库只支持主线程。

    所有方法都应该从 Ui 线程调用,所有异步回调也将在 Ui 线程上返回。

    参考:https://developer.android.com/reference/com/android/billingclient/api/BillingClient.html?hl=ko

    所以我修复了我的代码:

    fun consume() {
        verifyCompletable.subscribeOn(ioScheduler)
                .observeOn(uiScheduler)
                .andThen(consumePlayStore())
                .observeOn(ioScheduler)
                .flatMap(otherJob)
                .subscribeOn(ioScheduler)
                .observeOn(uiScheduler)
                .subscribe()
    }
    

    这段代码工作正常,但我不知道这是一个漂亮的解决方案。

    调度器看起来很复杂...

    【讨论】:

    • 无需订阅两次,链上只能有一个起点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    相关资源
    最近更新 更多