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

前端 未结 8 2123
闹比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 17:43

    Async and Launch, both are used to create coroutines that run in the background. In almost every situation one can use either of them.

    tl;dr version:

    When you dont care about the task's return value, and just want to run it, you may use Launch. If you need the return type from the task/coroutine you should use async.

    Alternate: However, I feel the above difference/approach is a consequence of thinking in terms of Java/one thread per request model. Coroutines are so inexpensive, that if you want to do something from the return value of some task/coroutine(lets say a service call) you are better off creating a new coroutine from that one. If you want a coroutine to wait for another coroutine to transfer some data, I would recommend using channels and not the return value from Deferred object. Using channels and creating as much number of coroutines as required, is the better way IMO

    Detailed answer:

    The only difference is in the return type and what functionality it provides.

    Launch returns Job while Async returns Deferred. Interestingly enough, Deferred extends Job. Which implies it must be providing additional functionality on top of Job. Deferred is type parameterised over where T is the return type. Thus, Deferred object can return some response from the block of code executed by async method.

    p.s. I only wrote this answer because I saw some factually incorrect answers on this question and wanted to clarify the concept for everyone. Also, while working on a pet project myself I faced similar problem because of previous Java background.

提交回复
热议问题