如何在没有 OnNext 的情况下使用 RxJava 抛出异常

How to throw an exception using RxJava without OnNext

我试图在使用 RxJava 进行虚假下载时强制抛出错误:

 disposable.add(fakeRepo.downloadSomething()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                { a: String -> finished() },
                { b: Throwable? -> showError() }
            ))


fun downloadSomething(): Single<String> {
        return Single.just("")
    }

我只找到了 onNext 的解决方案,但我不想在我的代码中使用它。

我应该怎么做才能调用 showError()? 目前我总是得到 finished()

只需使用Single.error:

http://reactivex.io/RxJava/javadoc/io/reactivex/Single.html#error-java.lang.Throwable-

public static Single error(Throwable exception) Returns a Single that invokes a subscriber's onError method when the subscriber subscribes to it.