Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Extension Function on Observable<T>.subscribe does not work

I'm trying to write an extension function for Observable.subscribe which automatically logs errors.

fun <T> Observable<T>.subscribeAndLogE(onNext: Consumer<in T>): Disposable =
    subscribe(onNext, ErrorConsumer())

The ErrorConsumer works and presumably logs the error, but subscribeAndLogE does not accept lambdas like .subscribe() does.

observer.subscribe { 
                //works
           }

observer.subscribeAndLogE { 
                //does not work
           }

It says:

error

With that OnboardingScreen being whichever value T would normally be.

I don't see the original Consumer<in T> in Observable doing anything special to accept lambdas. What am I doing wrong here?

like image 446
Jacques.S Avatar asked Oct 01 '18 09:10

Jacques.S


1 Answers

You are passing a parameter of type Consumer to the function. You need to pass a function for the lambda syntax to work. This would work the way you want to:

fun <T> Observable<T>.subscribeAndLogE(onNext: (it : T) -> Unit): Disposable =
        subscribe({ onNext(it) },{ throwable -> Log(throwable) })

and use it like so:

observer.subscribeAndLogE { 
                //works
           }
like image 189
Rado Avatar answered Nov 08 '22 05:11

Rado