[英]How run doOnSubscribe on MainThread in this case
I want to execute doOnSubscribe block on the main thread.我想在主线程上执行 doOnSubscribe 块。 I'm trying this:我正在尝试这个:
fun test(){
Single
.fromCallable {
print(Thread.currentThread())
getCachedProfile()
}
.observeOn(AndroidSchedulers.mainThread())
.flatMap {
print(Thread.currentThread())
api
.getProfile()
.doOnSubscribe {
print(Thread.currentThread())
}
.observeOn(Schedulers.io())
.map {
print(Thread.currentThread())
it.profile
}
.map { it.id }
.flatMap { photoId ->
print(Thread.currentThread())
api
.getPhotos(photoId)
.map { it.toDomain() }
}
}.subscribeOn(Schedulers.io())
.observeOn(AndroidSchdulers.mainThread())
}
doOnSubscribe run on the main thread, but .getProfile() run on UI thread too and I get an error NetworkOnMainThreadException. doOnSubscribe 在主线程上运行,但 .getProfile() 也在 UI 线程上运行,我收到错误 NetworkOnMainThreadException。 How set the schedulers so doOnSubscribe is executed on the main thread and getProfile() run on the IO thread如何设置调度器,所以 doOnSubscribe 在主线程上执行,getProfile() 在 IO 线程上运行
Add .subscribeOn(Schedulers.io)
to your .getProfile()
call so, .getProfile().subscribeOn(Schedulers.io).observeOn(AndroidSchedulers.mainThread().doOnSubscribe()
将.subscribeOn(Schedulers.io)
添加到您的.getProfile()
调用中, .getProfile().subscribeOn(Schedulers.io).observeOn(AndroidSchedulers.mainThread().doOnSubscribe()
This is how it's done in java, I imagine Kotlin has the same.这就是它在 Java 中的实现方式,我想 Kotlin 也是如此。
.doOnSubscribe{}
is calling something to do before the task is executed .doOnSubscribe{}
在任务执行之前调用了一些要做的事情
.subscribeOn()
tells what thread to do the work on .subscribeOn()
告诉在哪个线程上进行工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.