2017-12-03 193 views
1

我正在做一個listview什麼時候點擊調用函數。Kotlin中的異步匿名函數? (lambda表達式)

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

回答

2

你可以有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 
      } 
     }) 
+0

謝謝。你幫了我很多。但它在UI線程上。所以我必須嘗試阻止點擊。以及如何獲得'''isAsync()'''''如果我使用List '''????不可能??我嘗試'''如果(func是(suspend() - > Unit)''',它不起作用.... –

+0

並且這段代碼不起作用。T_T ...因爲run {}是內嵌的所以它不會返回'''() - > Unit''' –

+0

請參閱編輯另一個替代方案 –