我正在制作列表视图点击时的呼叫功能。
和I want to get function is async or sync
。
在异步时阻止。
甚至我想知道how attach async mark to kotlin lambda expression
。
class FunctionCaller_Content(text: List<String>,
val function: List< /*suspend? @async? */
( () -> Unit )?
>? = null)
/* I want both of async, sync function. */
{
fun isAsnyc(order: Int): Boolean
= // how to get this lambda expression{function?.get(order)} is async?
fun call(callerActivity: Activity, order: Int) {
val fun = function?.get(order)
fun()
if(isAsync(fun))
/* block click for async func */
}
}
和用法。
FunctionCaller_Content( listOf("Click to Toast1", "Click to Nothing"),
listOf(
{
Toast.makeText(this, "clicked", Toast.LENGTH_SHORT)
},
{
/*if async lambda expression, how can i do?*/
} )
答案 0 :(得分:2)
您可以拥有List<suspend () -> Unit>
,但除了使用List<Any>
之外,您无法在同一列表中同时拥有暂停和非暂停功能。我建议改用两个单独的列表。另一种解决方案是使用&#34;代数数据类型&#34;:
sealed class SyncOrAsync // can add methods here
class Sync(val f: () -> Unit) : SyncOrAsync
class Async(val f: suspend () -> Unit) : SyncOrAsync
class FunctionCaller_Content(text: List<String>,
val function: List<SyncOrAsync>? = null)
{
fun call(callerActivity: Activity, order: Int) {
val fun = function?.get(order)
if(fun is Async)
/* block click for async func */
}
}
FunctionCaller_Content(
listOf("Click to Toast1", "Click to Nothing"),
listOf(Sync {
Toast.makeText(this, "clicked", Toast.LENGTH_SHORT)
},
Async {
// your async code
})
但是如果你要阻止,我只会使用List<() -> Unit>
和
listOf({
Toast.makeText(this, "clicked", Toast.LENGTH_SHORT)
},
{
runBlocking {
// your async code
}
})