Android 对这个可观察对象进行编码以获取位置的正确方法是什么?
我正在编写一个observable来帮助我获取用户的国家代码(随后将其传递给另一个observable。这是我编写的代码:Android 对这个可观察对象进行编码以获取位置的正确方法是什么?,android,reactive-programming,rx-java2,rx-android,Android,Reactive Programming,Rx Java2,Rx Android,我正在编写一个observable来帮助我获取用户的国家代码(随后将其传递给另一个observable。这是我编写的代码: val tm: TelephonyManager = requireContext().getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager var countryCodeValue: String = tm.networkCountryIso.toUpperCase(Locale.ROOT) di
val tm: TelephonyManager = requireContext().getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
var countryCodeValue: String = tm.networkCountryIso.toUpperCase(Locale.ROOT)
disposables.add(Observable.just(countryCodeValue)
.flatMap {
if(it.isEmpty()) {
rxLocation.location()
.lastLocation()
.flatMap {
rxLocation.geocoding().fromLocation(it).map { item -> item.countryCode }
}
} else {
Observable.just(it)
}
}
.subscribe ({
Timber.i("Got country code: %s", it)
}, { error -> Timber.i("Got error $error")}))
我在这里做什么?从Context.TELEPHONY_服务中获取国家代码。如果它返回空字符串,则调用操作员根据用户位置获取地理编码的国家代码值
it.isEmpty()块完全失败,并给出一个错误,表示“类型不匹配”。这是令人惊讶的,因为flatMap应该像预期的那样发出字符串,但它没有。如何修复此问题?在阅读注释后解决了它,我应该使用flapmaybe 工作代码现在是:
disposables.add(Observable.just(countryCodeValue)
.flatMapMaybe {
if(it.isEmpty()) {
rxLocation.location()
.lastLocation()
.flatMap {
rxLocation.geocoding().fromLocation(it).map { item -> item.countryCode }
}
} else {
Maybe.just(it)
}
}
.subscribe ({
Timber.i("Got %s", it)
}, { error -> Timber.i("Got error $error")}))
flatMap
是否应该是一个flatmappaye
?查看源代码a Maybe是唯一一个为GeoCoding::fromLocation
接受单参数参数参数的返回类型是的,你说得对。我现在知道了。