RxJava - 等待异步任务然后调用 Api

RxJava - wait for async task and then call Api

正在尝试获取 lastLocation,完成后调用 api。但是不知何故,一旦获得位置,我的 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函数有什么关系吗?

subscribeOnobserveOnsubscribe 的顺序和转换很重要。显然,它需要进行转换,在这种情况下,flatMap after 指定带有 observeOn 的观察者线程以确保代码正确执行线程。