我正在尝试学习 Kotlin
和 rxjava
。我有一个非常简单的应用程序,只有一个按钮
,单击该按钮即可从网站获取一些数据。
除非我关闭蜂窝数据,否则一切正常,在这种情况下,我会遇到致命异常,并且没有解释原因。
My code:
// In the activity's onCreate
ViewObservable.clicks(button)
.observeOn(Schedulers.io())
.subscribe{
fetchTest().observeOn(AndroidSchedulers.mainThread())
.subscribe{ s:String ->
textView.text = s
}
}
// Elsewhere in the activity code
@Throws(IOException::class)
private fun fetchTest(): Observable<String> {
val url = URL(MY_URL)
val httpConnection = url.openConnection()
var stream = httpConnection.inputStream
val reader = BufferedReader(InputStreamReader(stream))
val response = reader.readLines().reduce { x, y -> x + y }
stream?.close()
return Observable.just(response)
}
When I'm in debug mode, the error occurs here:
var stream = httpConnection.inputStream
logcat 完全没有帮助:
02-12 10:13:37.748 8616-8645/com.example.app E/AndroidRuntime﹕ FATAL EXCEPTION: RxCachedThreadScheduler-1
Process: com.example.app, PID: 8616
我知道错误是因为没有网络连接,但是添加 try/catch 无法捕获它,所以我不知道该怎么办
最佳答案
View 可观察对象的订阅者也需要实现 onError
关于android - 未连接互联网时出现致命异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35366354/