Created
March 23, 2017 09:17
-
-
Save punksta/d0304886df8beb8c6d3cdaa8e14c738c to your computer and use it in GitHub Desktop.
error catching decorator for retrofit instance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import rx.Observable | |
import rx.Single | |
import java.lang.reflect.InvocationHandler | |
import java.lang.reflect.Method | |
import java.lang.reflect.Proxy | |
/** | |
* Created by punksta on 18.10.16. | |
*/ | |
object ErrorApiDecorator : IApiDecorator { | |
override fun <T : I, I> decorate(api: T, clazz: Class<I>): I { | |
return decorateErrors(api, clazz) | |
} | |
fun <T : I, I> decorateErrors(api: T, clazz: Class<I>): I { | |
val handler: InvocationHandler = InvocationHandler { any: Any?, method: Method, arrayOfAny: Array<out Any>? -> | |
method.invoke(api, *arrayOfAny.orEmpty()) | |
.let { | |
when (it) { | |
is Single<*> -> it.doOnError { | |
RxEventBus.postEvent(it) | |
} | |
is Observable<*> -> it.doOnError { | |
RxEventBus.postEvent(it) | |
} | |
else -> it | |
} | |
} | |
} | |
val proxy = Proxy.newProxyInstance(clazz.classLoader, arrayOf(clazz), handler) | |
return proxy as I | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment