Generic – rxkotlin: attempt to add custom error capture
I'm trying to write my own extension function for rxkotlin, which will make observable handle a specific error type (throwable subclass), and its handler will be passed as a parameter and no more items will be issued
The marble will be:
--- a --- b --- c --- error : T [ handleError<T>(handler) ] --- a --- b --- c --- finished | handler(error)
I wrote the following:
public inline fun <reified E : Throwable,R> Observable<R>.handleError( crossinline handler: (E) -> Unit ) = onErrorResumeNext f@{ return@f when (e) { is E -> { handler(e); Observable.empty() } else -> Observable.error(e) } }
It works normally, but to use it, I must write, for example:
val myObservable: Observable<SomeClass> = ... myObservable.handleError<IOException,SomeClass> { it.printStackTrace() } ^^^^^^^^^
I don't like that I have to write observable generics in the handleerror call, and I want to avoid it
So, is there any way to avoid explicitly specifying the second general parameter?
I think once I specify a generic parameter, there is no way for the compiler to infer it But is there a way to rewrite handleerrors to achieve what I want?
Solution
First, to specify e explicitly, you can use more detailed lambda syntax It looks like this:
myObservable.handleError { it : IOException -> it.printStackTrace() }
Alternatively, you can add an additional parameter to help the compiler infer the type It looks like this:
public inline fun <reified E : Throwable,R> Observable<R>.handleError( typeHint: (E) -> Unit,crossinline handler: (E) -> Unit ) = onErrorResumeNext f@{ return@f when (e) { is E -> { handler(e); Observable.empty() } else -> Observable.error(e) } } fun <T> of() : (T) -> Unit = {}
Usage:
myObservable.handleError(of<IOException>()) { it.printStackTrace() }