我正在尝试订阅一个SingleSource
,我已经实现了onSuccess
和subscribe
方法的onError
,这是我的代码:
disposable.add(repository
.getUser1()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
toast(it)
}, {
toast(it.message ?: "Error")
}))
问题是当存储库中发生异常时,它不会被捕获onError
这是我的存储库实现:
class Repository(private val sp: SharedPreferences) {
// It crashes
fun getUser1(): Single<String> = generateUser(name, "Hello")
// it doesn't crash
fun getUser2(): Single<String> = Single.fromCallable { name }.flatMap { generateUser(it, "Hello") }
private var name: String
get() = sp.getString("user", null) ?: throw NoNameException()
set(value) = sp.edit().putString("user", value).apply()
private fun generateUser(name: String, message: String): Single<String> = Single.just("$message $name")
}
这是崩溃日志:
09-24 10:13:40.930 6934-6934/com.mosius.samplerxtest E/AndroidRuntime: 致命例外:主要 进程: com.mosius.samplerxtest, PID: 6934 java.lang.RuntimeException: java.lang.reflect.InvocationTargetException at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:503( at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826( 由: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method( at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493( at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826( 由以下原因引起:com.mosius.samplerxtest.NoName异常:未提供名称 at com.mosius.samplerxtest.Repository.getName(Repository.kt:17( at com.mosius.samplerxtest.Repository.getUser1(Repository.kt:10( at com.mosius.samplerxtest.MainActivity$onCreate$1.onClick(MainActivity.kt:24( at android.view.View.performClick(View.java:6597( at android.view.View.performClickInternal(View.java:6574( at android.view.View.access$3100(View.java:778( at android.view.View$PerformClick.run(View.java:25881( at android.os.Handler.handleCallback(Handler.java:873( at android.os.Handler.dispatchMessage(Handler.java:99( at android.os.Looper.loop(Looper.java:164( at android.app.ActivityThread.main(ActivityThread.java:6649( at java.lang.reflect.Method.invoke(Native Method( at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493( at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826(
这两种实现之间有什么区别?
在getUser1()
方法中,尚未创建SingleSource
,因此无法处理异常。
在第二个中,名称正在 Rx 范围内获取,因此它可以处理异常