簡體   English   中英

Kotlin協程在UI線程上等待

[英]Kotlin coroutine await on UI thread

目前,在我的代碼庫中,使用Kotlin ,我有一個擴展功能,該功能可以按以下方式工作。

async {
    executeSomeCodeToGetResult()
}.awaitOnUiThread { result ->
    useResultOnUiThread(result)
}

async函數將可運行對象加載到ExecutorService ,該服務將返回Future<T>結果。 awaitOnUiThreadFuture<T>對象上的擴展函數,該函數將T作為參數發送給輸入函數。

我想知道是否有使用Kotlin coroutines實現類似結果的方法?

我確實實現了類似的方法,但是沒有得到很好的性能結果。 也許我在GlobalScope上運行await()函數做錯了什么?

private const val threadPoolSize = 4

@ObsoleteCoroutinesApi
val scope = CoroutineScope(newFixedThreadPoolContext(threadPoolSize, "async-runner"))

@ObsoleteCoroutinesApi
fun <T> async(function: () -> T): Deferred<T> {
    return scope.async { function() }
}

fun <T> Deferred<T>.awaitOnUiThread(function: (T) -> Unit) {
    val deferred = this
    GlobalScope.launch {
        val result: T = deferred.await()
        Handler(Looper.getMainLooper()).post {
            function(result)
        }
    }
}

使用協程,您不需要asyncawaitOnGuiThread 您應該使用以下成語:

launch(Dispatchers.Main) {
    val result = withContext(Dispatchers.IO) {
        executeSomeCodeToGetResult()
    }
    ... just keep using the result
}

至少這是一個粗略的第一近似。 Kotlin的協程系統希望您也明確處理失敗和取消。 本主題以結構化並發的名稱命名。 最好的起點是ViewModel因為它具有對結構化並發的內置支持

暫無
暫無

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

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