1

Using RxJava on Kotlin Android, what am I doing is -

I have a function to create a Bitmap which I'm running in an IO thread.

After the Bitmap is ready, I'm setting it to an ImageView on the main thread.

var observable : Observable<Bitmap> = Observable.just(makeBitmap(path))

var observer:Observer<Bitmap> = io.reactivex.Observer<Bitmap>() {
                fun onSubscribe(d: Disposable) {
                    disposable = d
                }
                fun onNext(bitmap) {
                   imageView.setImageBitmap(bitmap)
                }
                fun onError(e:Throwable) {
                }
                fun onComplete() {
                }
            }

observable.subscribeOn(Schedulers.io())
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe(observer)

My question is, can we achieve something like this using LiveData and by Observing the data in architecture components ?

Basically I want to observe something on main thread but the heavy work has to be done on a separate thread.

Gissipi_453
  • 1,250
  • 1
  • 25
  • 61
  • see [LiveData#postValue](https://developer.android.com/reference/android/arch/lifecycle/LiveData.html#postValue(T)) – pskink May 31 '18 at 14:58
  • Check this related question : https://stackoverflow.com/questions/49122299/convert-rxjava-observables-to-live-data-with-kotlin-extension-functions – crgarridos May 31 '18 at 15:14

1 Answers1

2

Well, you could have something like this:

var bitmapLiveData: MutableLiveData<Bitmap> = MutableLiveData()

fun createBitmap(): LiveData<Bitmap> {

        var observable : Observable<Bitmap> = Observable.just(makeBitmap(path))
        val result = observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    result ->
                    bitmapLiveData.postValue(result)
                },{
                    error->
                    error.printStackTrace()
                },{
                    //completed
                })

        return bitmapLiveData

    }

I put that in a view model that can be observed by a LifecycleOwner:

 viewModel.createBitmap().observe(this, Observer { 
            it?.let { 
                //result bitmap
            }
        })
Levi Moreira
  • 11,917
  • 4
  • 32
  • 46