我正在使用适用于Android的库Reactive Network。我是RxJava的绝对初学者,我试图绕过它。我想做的是:
1]持续观察手机网络连接状态的变化
2]如果手机已连接到网络,请检查是否有互联网连接
为此,我在Kotlin中有以下代码:
ReactiveNetwork.observeNetworkConnectivity(applicationContext)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { connectivity ->
if (connectivity.state == NetworkInfo.State.CONNECTED) {
ReactiveNetwork.checkInternetConnectivity()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { isConnectedToInternet ->
if (isConnectedToInternet) {
Log.d("VED-APP", "Connected to Internet")
} else {
Log.d("VED-APP", "Not Connected to Internet")
}
}
}
}
但是,这段代码很难看并且非常嵌套。有没有办法清理这段代码?
虽然样本在Kotlin中,但Java或Kotlin中的答案都会有所帮助。
答案 0 :(得分:3)
您可以过滤connectivity.state,然后使用flatmap运算符将observable转换为ReactiveNetwork.checkInternetConnectivity()。如:
ReactiveNetwork.observeNetworkConnectivity(applicationContext)
.subscribeOn(Schedulers.io())
.filter{it.state == NetworkInfo.State.CONNECTED}
.flatMapSingle{ReactiveNetwork.checkInternetConnectivity()}
.observeOn(AndroidSchedulers.mainThread())
.doOnNext{
if (it) {
Log.d("VED-APP", "Connected to Internet")
} else {
Log.d("VED-APP", "Not Connected to Internet")
}
}
.subscribe()