Skip to content

Instantly share code, notes, and snippets.

Last active February 6, 2020 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hiperbou/283e6531fb2b71b324d5064f820df889 to your computer and use it in GitHub Desktop.
Save hiperbou/283e6531fb2b71b324d5064f820df889 to your computer and use it in GitHub Desktop.
package com.hiperbou.test
import junit.framework.TestCase
import kotlinx.coroutines.*
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy
import kotlin.coroutines.Continuation
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.coroutines.resume
class SuspendProxyTest : TestCase() {
interface Adder{
suspend fun add(a:Int, b:Int):Int
fun addSync(a:Int, b:Int):Int
class SuspendHandler(private val delegate:Adder, private val ctx: CoroutineContext, private val onResult:(Any?)->Unit):InvocationHandler {
override fun invoke(proxy: Any, method: Method, arguments: Array<Any>): Any {
val function = method.kotlinFunction!!
return if (function.isSuspend) {
val parameters = arguments.copyOf(arguments.size - 1)
val continuation = arguments.last() as Continuation<Any?>
method.invoke(delegate, *parameters, Continuation<Any?>(ctx) {
it.getOrNull().apply {
} else {
val parameters = arguments ?: arrayOf()
method.invoke(delegate, *parameters).apply(onResult)
fun testCacheSimple() = runBlocking {
val delegate = object:Adder {
override suspend fun add(a:Int, b:Int):Int {
println("delay 1")
println("delay 2")
println("delay 3")
return a + b
override fun addSync(a:Int, b:Int):Int {
return a + b
val adder = Proxy.newProxyInstance(,
SuspendHandler(delegate, EmptyCoroutineContext) {
println("This is the result! $it")
) as Adder
val result = adder.add(1,3)
val result2 = adder.addSync(1,3)
Copy link

vicboma1 commented Feb 5, 2020

Muchita mágia hay aquí!
No sé porque falla...

Copy link

hiperbou commented Feb 6, 2020


Copy link

vicboma1 commented Feb 6, 2020

He visto los deltas.
Has cambiado bastantes cositas 😉
Ya me lo enseñarás en vivo 😚😚😚

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment