[英]Kotlin coroutine await on UI thread
目前,在我的代碼庫中,使用Kotlin
,我有一個擴展功能,該功能可以按以下方式工作。
async {
executeSomeCodeToGetResult()
}.awaitOnUiThread { result ->
useResultOnUiThread(result)
}
async
函數將可運行對象加載到ExecutorService
,該服務將返回Future<T>
結果。 awaitOnUiThread
是Future<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)
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.