-
-
Save hiperbou/283e6531fb2b71b324d5064f820df889 to your computer and use it in GitHub Desktop.
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
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 { | |
onResult(this) | |
continuation.resume(this) | |
} | |
}) | |
} 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") | |
delay(1000) | |
println("delay 2") | |
delay(1000) | |
println("delay 3") | |
delay(1000) | |
return a + b | |
} | |
override fun addSync(a:Int, b:Int):Int { | |
return a + b | |
} | |
} | |
val adder = Proxy.newProxyInstance( | |
Adder::class.java.classLoader, | |
arrayOf(Adder::class.java), | |
SuspendHandler(delegate, EmptyCoroutineContext) { | |
println("This is the result! $it") | |
} | |
) as Adder | |
val result = adder.add(1,3) | |
val result2 = adder.addSync(1,3) | |
println(result) | |
println(result2) | |
} | |
} |
Solucionado.
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
Muchita mágia hay aquí!
No sé porque falla...