Search code examples
androidkotlinrx-java2rx-androidrx-kotlin

How to create a extension function to make rx subscription to flowable cleaner?


I'm developing an android app using room and RxAndroid. The problem is that i'm using the next code to refresh the info in my recycler view.

observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe{adapter.data = it}

if i implement this in my activity it works like a charm. But i want to create an extension function to make the code cleaner when using flowables from the database. I create this funtion

fun <T> Flowable<T>.uiSubscribe(x : (T) -> Unit)  {
this.subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe{x}

but when i tried to use it, it does nothing. It doesn't trow an error or anything. Does somebody know a way to archive this? or does somebody know why it is not working?


Solution

  • You should use subscribe { x(it) } or subscribe(x).

    In your case subscribe{x} creates an onNext consumer which does nothing but state x in the expression.