Search code examples
androidrx-java2android-livedata

How to return error from Rxjava Flowable when using LiveDataReactiveStreams?


I am trying to return error from Rxjava stream but it shows error in return type.

Here is the code.


    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())
    }

}

Here is my Resource 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)
        }
    }
}

I am unable to find any reference regarding this issue.


Solution

  • onErrorReturn would expect return type same as that of shopRepo.getCategories().

    If you move the chain call for onErrorReturn after map, it would work as the map will transform the type.

    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) }