Why does thread changed to Main thread in callback?

青春壹個敷衍的年華 提交于 2020-03-05 00:30:33

问题


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

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

But the library only support async callback.

So I make a code like:

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?

Somebody tell me why?

And how can I solve this problem???

or better design???


回答1:


I found the reason and a solution.

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

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.

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

So I fixed my code like:

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



来源:https://stackoverflow.com/questions/60172733/why-does-thread-changed-to-main-thread-in-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!