ininmm
ininmm

Reputation: 552

android - How to handle error by using LiveData and RxJava?

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?

Upvotes: 1

Views: 1386

Answers (1)

Sergey Buzin
Sergey Buzin

Reputation: 255

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

Upvotes: 1

Related Questions