我正在编写一个Observable,以帮助我获取用户的国家/地区代码(然后将其传递给其他Observable。这是我编写的代码:
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_SERVICE中获取国家/地区代码。如果返回空字符串,则调用RxLocation运算符以根据用户位置获取经过地理编码的国家代码值。
it.isEmpty()块完全失败,并显示错误消息“ Type Mismatch”。这是令人惊讶的,因为flatMap应该发出预期的字符串,但事实并非如此。如何解决这个问题?
在阅读了Mark Keen的评论后解决了该问题,我应该使用flapMapMaybe