Created
May 14, 2021 11:48
-
-
Save RomanPozdeev/4cfb5a3693f5969b98e5927a412bf18e to your computer and use it in GitHub Desktop.
retrofit coroutines workaround
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 kotlinx.coroutines.runBlocking | |
import kotlinx.coroutines.withContext | |
import retrofit2.Retrofit | |
import java.lang.reflect.InvocationHandler | |
import java.lang.reflect.Method | |
import java.lang.reflect.Proxy | |
import kotlin.coroutines.Continuation | |
import kotlin.coroutines.CoroutineContext | |
private typealias Invoke = suspend (proxy: Any, method: Method, args: Array<*>) -> Any? | |
object RetrofitFix { | |
@Suppress("UNCHECKED_CAST") | |
fun <T> create(retrofit: Retrofit, context: CoroutineContext, service: Class<T>): T { | |
val delegate = retrofit.create(service) | |
val invoke: Invoke = { _: Any, method: Method, args: Array<*> -> | |
applyDispatcher(context) { | |
method.invoke(delegate, *args) | |
} | |
} | |
val invocationHandler = suspendInvocationHandler(invoke) | |
return Proxy.newProxyInstance( | |
service.classLoader, | |
arrayOf<Class<*>>(service), | |
invocationHandler | |
) as T | |
} | |
private suspend inline fun applyDispatcher( | |
context: CoroutineContext, | |
crossinline method: () -> Any? | |
) { | |
withContext(context) { | |
method() | |
} | |
} | |
private fun suspendInvocationHandler(block: Invoke): InvocationHandler { | |
return InvocationHandler { proxy, method, args -> | |
val cont = args?.lastOrNull() as? Continuation<*> | |
if (cont == null) { | |
val methodArgs = args.orEmpty() | |
runBlocking { | |
block(proxy, method, methodArgs) | |
} | |
} else { | |
@Suppress("UNCHECKED_CAST") | |
val suspendInvoker = block as (Any, Method, Array<*>?, Continuation<*>) -> Any? | |
suspendInvoker(proxy, method, args, cont) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
старая добрая java спешит на помощь