Kotlin: withContext() vs Async-await

前端 未结 3 1057
栀梦
栀梦 2020-12-22 17:00

I have been reading kotlin docs, and if I understood correctly the two Kotlin functions work as follows :

  1. withContext(context): switches the contex
3条回答
  •  长情又很酷
    2020-12-22 17:26

    Isn't it always better to use withContext rather than asynch-await as it is funcationally similar, but doesn't create another coroutine. Large numebrs coroutines, though lightweight could still be a problem in demanding applications

    Is there a case asynch-await is more preferable to withContext

    You should use async/await when you want to execute multiple tasks concurrently, for example:

    runBlocking {
        val deferredResults = arrayListOf>()
    
        deferredResults += async {
            delay(1, TimeUnit.SECONDS)
            "1"
        }
    
        deferredResults += async {
            delay(1, TimeUnit.SECONDS)
            "2"
        }
    
        deferredResults += async {
            delay(1, TimeUnit.SECONDS)
            "3"
        }
    
        //wait for all results (at this point tasks are running)
        val results = deferredResults.map { it.await() }
        println(results)
    }
    

    If you don't need to run multiple tasks concurrently you can use withContext.

提交回复
热议问题