简体   繁体   English

Kotlin 反射与协程

[英]Kotlin reflection with coroutines

I need to call the method suspend fun insert(e: T) by reflection declared as follows:我需要通过反射调用方法suspend fun insert(e: T) ,声明如下:

interface IMutableDao<T> {

    @Insert(onConflict = OnConflictStrategy.ABORT)
    suspend fun insert(e: T)

    @Update
    suspend fun update(e: T)

    @Delete
    suspend fun delete(e: T)
}

I tried with:我试过:

val insertFun = IMutableDao::class.functions.find {
            it.name.equals("insert", true)
        }
insertFun!!.callSuspend(dao, o)

But I get the exception " Callable expects 3 arguments, but 2 were provided. ".但我得到了异常“ Callable expects 3 arguments, but 2 were provided. ”。 I do not understand where the 3rd argument comes from.我不明白第三个论点来自哪里。

UPDATE更新

I have found the problem.我发现了问题。 The 3rd is a Continuation instance.第三个是一个 Continuation 实例。 Does anyone know what to pass there?有谁知道在那里通过什么? I couldn't find any suitable instance.我找不到任何合适的实例。

UPDATE 2更新 2

The workaround I found was to create a temporary class inside the function I call the suspended function from, like this:我找到的解决方法是在 function 中创建一个临时 class 我称之为暂停的 function ,如下所示:

val c = object : Continuation<Unit> {
override val context: CoroutineContext
get() = EmptyCoroutineContext
        override fun resumeWith(result: Result<Unit>) {
    }
}

You are missing the "this" parameter which is the object that the method should be called with respect to.您缺少“this”参数,即 object 应该调用该方法。

it should be the first argument to the method.它应该是该方法的第一个参数。

You may use suspendCoroutine with Unit as type and use the continuation instance.您可以使用带有 Unit 作为类型的suspendCoroutine并使用延续实例。

GlobalScope.launch {
    suspendCoroutine<Unit> { continuation ->
        insertFun!!.callSuspend(dao, o, continuation)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM