使用 retrofit 在 mvvm 中处理 Rxjava 的错误

Error Handling of Rxjava in mvvm using retrofit

我正在调用一个 api,它给出 Http 状态代码 400

这是我的 NetworkBoundResourceNoDb

public abstract class NetworkBoundResourceNoDb<RequestType> {

    private Observable<Resource<RequestType>> result;

    @MainThread
    protected NetworkBoundResourceNoDb() {
        Observable<Resource<RequestType>> source;
        source = createCall()
            .subscribeOn(Schedulers.io())
            .doOnError(t -> onFetchFailed())
            .observeOn(AndroidSchedulers.mainThread());

        result = Observable.ambArray(source);
    }


    public Observable<Resource<RequestType>> getAsObservable() {return result;}

    protected boolean onFetchFailed() {
        return false;
    }


    @NonNull
    @MainThread
    protected abstract Observable<Resource<RequestType>> createCall();
}

这是API代码

@GET("api/content/count")
Observable<List<WordCountData>> wordCount();

这是存储库功能

    fun wordCount(): Observable<Resource<List<WordCountData>>>? {
    return object : NetworkBoundResourceNoDb<List<WordCountData>>() {

        override fun createCall(): Observable<Resource<List<WordCountData>>> {
            return courseApi.wordCount()
                .flatMap { learntWords ->
                    Observable.just(
                        if (learntWords == null) Resource.error("", emptyList())
                        else Resource.success(learntWords)
                    )
                }
        }

    }.asObservable
}

这是视图模型代码

private var wordCount = MutableLiveData<Resource<List<WordCountData>>>()

fun getWordCountLiveData() = wordCount

fun getWordCountList() {
    courseRepository.wordCount()?.subscribe { resource -> getWordCountLiveData().postValue(resource) }
}

这是我的查看代码

private fun loadWordCount() {
    crViewModel = ViewModelProviders.of(this, viewModelFactory).get(CrViewModel::class.java)
    crViewModel.getWordCountLiveData().observe(this, androidx.lifecycle.Observer {
        resource -> when {
        resource.isLoading -> println("loading")
        resource.data != null -> {
            drawChart(resource.data)
        }
        else -> handleErrorResponse()
    }
    })
    crViewModel.getWordCountList()
}

我需要传递Http Status代码才能查看。在使用 throwable 参数实现它时,我能够在存储库中的 onFetchfailed 中得到错误,但在那之后无法处理它

它给我 "io.reactivex.exceptions.OnErrorNotImplementedException: HTTP 400 " 错误

请帮助我提前谢谢

伙计,你在 1.

中问了很多问题
fun getWordCountList() {
courseRepository.wordCount()?.subscribe { resource -> getWordCountLiveData().postValue(resource) }
}

这是触发所有其他网络代码的代码块。 但是,这个 lambda 只有成功参数,没有错误参数。添加第二个 lambda,并用括号括起来,以说明成功和失败:

.subscribe({
    successResponse -> // handle success
}, 
{ error -> // handle error
})

所以,至少应该处理 "OnErrorNotImplementedException"

错误 400 通常意味着您的请求无效,and/or您向请求传递了错误的参数集。我无法根据您提供给我们的大量信息帮助您,而且我对您的服务器一无所知。

最后:"I need to pass Http Status code to view"。什么??为什么? 你的标题甚至提到建筑!为什么你的视图层甚至关心来自网络调用的响应代码?

不要那样做。当然,您的视图 "can" 知道响应代码,但这是视图层根本不应该知道的东西。

希望对您有所帮助。