为什么线程在回调中变为主线程? [英] Why does thread changed to Main thread in callback?

查看:85
本文介绍了为什么线程在回调中变为主线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Kotlin和RxJava开发一个android应用.

I am developing an android app using the Kotlin and RxJava.

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

I developed In-App billing using the android latest API.

但是该库仅支持异步回调.

But the library only support async callback.

所以我编写如下代码:

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


}

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

I don't know why the thread is changed in the callback?

有人告诉我为什么?

我该如何解决这个问题?

And how can I solve this problem???

或更好的设计?

推荐答案

我找到了原因和解决方案.

I found the reason and a solution.

首先,原因是Google InApp库仅支持主线程.

First, the reason is that the Google InApp library only supports the Main thread.

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

All methods are supposed to be called from the Ui thread and all the asynchronous callbacks will be returned on the Ui thread as well.

引用: 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()
}

此代码可以正常工作,但我不知道这是一个漂亮的解决方案.

This code works fine, but I don't know that this is a beautiful solution.

日程安排者看起来很复杂...

Schedulers look like very complicated...

这篇关于为什么线程在回调中变为主线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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