为什么线程在回调中变为主线程?
Why does thread changed to Main thread in callback?
我正在使用 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()
}
不知道回调中为什么要改线程?
有人告诉我为什么吗?
我该如何解决这个问题???
或更好的设计???
找到原因和解决办法
首先,原因是Google InApp库只支持主线程
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()
}
这段代码工作正常,但我不知道这是一个漂亮的解决方案。
调度器看起来很复杂...
我正在使用 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()
}
不知道回调中为什么要改线程?
有人告诉我为什么吗?
我该如何解决这个问题???
或更好的设计???
找到原因和解决办法
首先,原因是Google InApp库只支持主线程
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()
}
这段代码工作正常,但我不知道这是一个漂亮的解决方案。
调度器看起来很复杂...