1

I'm new for learning android architecture components and I have stuck in the question several days.

I use LiveDataReactiveStreams to transform Livedata and Flowable, all of them works well, except handling RxJava's onError.

        livedata = LiveDataReactiveStreams.fromPublisher(
            // bookRepository.getAll() return a Flowable
            bookRepository.getAll().map {
                val allBookNames = mutableListOf<String>()
                it.forEach {
                    allBookNames.add(it.name)
                }
                return@map allBookNames.toList()
            }
        )

I saw How to handle error states with LiveData? and figure out I can

  1. wrap my data to Handle my error

  2. or use MediatorLiveData as @Nikola Despotoski said, but there is an another question is Flowable onComplete() is never called.

Is there a better way to solve this question or any details about these two solutions I've ignored?

ininmm
  • 373
  • 2
  • 10
  • I think you need to use LiveData instead of RxJava. They're both observables. – Hades May 30 '18 at 03:42
  • @Hades But LiveData also doesn't provide any functions to handle errors. – ininmm May 30 '18 at 04:03
  • Depending on the implementation of your `bookRepository.getAll()` method, you could pass an error callback there as a parameter, and change the call to the following: bookRepository.getAll({//Handle error here}).map {//Handle success here}.etc... With this approach, your `getAll()` method would fire the callback and return null in case of error, or return the books in case of success – NSimon May 30 '18 at 08:33

1 Answers1

1
LiveDataReactiveStreams.fromPublisher(
            Observable.just(1,2)
                    .map { LiveDataResult(it, null) }
                    .onErrorReturn {
                        it.printStackTrace()
                        LiveDataResult(null, it)
                    }
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .toFlowable(BackpressureStrategy.MISSING)


class LiveDataResult<T>(val data: T?, val error: Throwable?)

Then inUI you can handle result or error

Sergey Buzin
  • 256
  • 2
  • 5