Skip to content

Instantly share code, notes, and snippets.

@hiperbou
Last active February 6, 2020 14:10
Show Gist options
  • 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 {
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)
}
}
@vicboma1
Copy link

vicboma1 commented Feb 5, 2020

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

@hiperbou
Copy link
Author

hiperbou commented Feb 6, 2020

Solucionado.

@vicboma1
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