尝试获取lastLocation
并在完成后调用api。但不知何故,一旦获得位置,我的应用程序接口调用总是在mainThread
中运行,所以我得到了异常:
android.io.NetworkOnMainThreadException
这里的是我的位置观察者:
fun getLocation(): Single<Location> {
return Single.create<Location> { subscriber ->
fusedLocationClient.lastLocation.addOnSuccessListener {
if (it != null) {
subscriber.onSuccess(it)
} else {
subscriber.onError(Exception("No location"))
}
}
}
}
执行一些转换的代码
val locationObserver = getLocation()
observables.add(locationObserver.flatMap { _ -> sendDataToServer(data)})
观察者
Single.zip(observables) { args1 -> args1 }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe({
Timber.i("Success")
}, {
Timber.i("Error %s", observables.size, it.localizedMessage)
it.printStackTrace()
})
我已经设置了subscribeOn
,所以它不应该在mainThread
上,但看起来好像遗漏了什么。
我发现,如果我使用像Single.just("One").flatMap{ ... }
这样的东西,它将工作得很好,并将在非主线程上执行。
和getLocation
函数有什么关系吗?
发布于 2019-03-26 06:23:57
subscribeOn
、observeOn
、subscribe
和转换的顺序很重要。显然,它需要进行转换,在本例中,是在使用observeOn
指定观察者线程之后的flatMap
,以确保代码在正确的线程中执行。
https://stackoverflow.com/questions/55346851
复制相似问题