问题
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