Trying to get lastLocation and once it's done call api. But somehow once location is obtained my api calls always running in mainThread, so i'm getting exception:
android.io.NetworkOnMainThreadException
Here is my location observer:
fun getLocation(): Single<Location> {
return Single.create<Location> { subscriber ->
fusedLocationClient.lastLocation.addOnSuccessListener {
if (it != null) {
subscriber.onSuccess(it)
} else {
subscriber.onError(Exception("No location"))
}
}
}
}
Code that does some transformations
val locationObserver = getLocation()
observables.add(locationObserver.flatMap { _ -> sendDataToServer(data)})
Observer
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()
})
I've set subscribeOn so it shouldn't be on mainThread, but looks like something missed.
Found that if i will use something like Single.just("One").flatMap{ ... } that will work fine and will be executed on non-main thread.
Is there something to do with getLocation function?