簡體   English   中英

Kotlin 中的異步匿名函數? (拉姆達表達式)

[英]Asynchronous anonymous function in Kotlin? (lambda expressions)

我正在制作一個列表視圖(android)點擊時調用什么函數。

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?*/
                        } )

您可以擁有List<suspend () -> Unit> ,但您不能在同一個列表中同時擁有掛起和非掛起功能,除非使用List<Any> 我建議改用兩個單獨的列表。 另一種解決方案是使用“代數數據類型”:

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
           }
       })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM