使用 LiveDataReactiveStreams 时如何从 Rxjava Flowable 中 return 错误?

How to return error from Rxjava Flowable when using LiveDataReactiveStreams?

我正在尝试 return 来自 Rxjava 流的错误,但它显示 return 类型错误。

这是代码。


    private fun getCategories(): Flowable<Resource<List<Category>>> {
        return shopRepo.getCategories()
            .subscribeOn(Schedulers.io())
            .onErrorReturn { Resource.error(it.message) }
            .doOnSubscribe { Resource.loading(true) }
            .map{
                Resource.success(it)
            }
    }

    fun observeCategories(): LiveData<Resource<List<Category>>> {
        return LiveDataReactiveStreams.fromPublisher(getCategories())
    }

}

这是我的资源Class

data class Resource<out T>(val status: Status, val data: T?, val message: String?) {
    enum class Status {
        SUCCESS,
        ERROR,
        LOADING
    }
    companion object {
        fun <T> success(data: T?): Resource<T> {
            return Resource(SUCCESS, data, null)
        }

        fun <T> error(msg: String, data: T?): Resource<T> {
            return Resource(ERROR, data, msg)
        }

        fun <T> loading(data: T?): Resource<T> {
            return Resource(LOADING, data, null)
        }
    }
}

我找不到关于这个问题的任何参考资料。

onErrorReturn 期望 return 类型与 shopRepo.getCategories() 相同。

如果您在 map 之后移动对 onErrorReturn 的链调用,它将起作用,因为映射将转换类型。

shopRepo.getCategories()
        .subscribeOn(Schedulers.io())
        .map{ Resource.success(it) }
        .observeOn(AndroidSchedulers.mainThread()) // You'll need this probably to move it the UI thread.
        .onErrorReturn { Resource.error(it.message) }
        .doOnSubscribe { Resource.loading(true) }