What is the difference between launch/join and async/await in Kotlin coroutines

前端 未结 8 2093
闹比i
闹比i 2020-11-30 17:17

In the kotlinx.coroutines library you can start new coroutine using either launch (with join) or async (with await<

相关标签:
8条回答
  • 2020-11-30 18:06

    Async vs Launch Async vs Launch Diff Image

    launch / async no result

    • Use when don't need result,
    • Don't block the code where is called,
    • Run in parallel

    async for result

    • When you need to wait the result and can run in parallel for efficiency
    • Block the code where is called
    • run in parallel
    0 讨论(0)
  • 2020-11-30 18:07

    launch returns a job

    async returns a result (deferred job)

    launch with join is used to wait until the job gets finished.it simply suspends the coroutine calling join(), leaving the current thread free to do other work (like executing another coroutine) in the meantime.

    async is used to compute some results. It creates a coroutine and returns its future result as an implementation of Deferred. The running coroutine is canceled when the resulting deferred is canceled.

    Consider an async method that returns a string value. If the async method is used without await it will return a Deferred string but if await is used you will get a string as the result

    The key difference between async and launch. Deferred returns a particular value of type T after your Coroutine finishes executing, whereas Job doesn’t.

    0 讨论(0)
提交回复
热议问题