RoadMovie

write down memos or something I found about tech things

Kotlinで新たに使えるようになったCoroutineで非同期処理

Coroutines Overview - Kotlin Programming Language

2019/01/16現在、まだexperimentalなのですが、使い勝手が良いので私が手伝っている会社でも取り入れ始めている、というより全面的にcoroutineで書き直しています。 基本的に launch の使い方と async, await の使い方を理解できれば良いだけなのでとっつきやすいと思います。

launch — This builder simply launches a new coroutine and returns a reference to it as a Job object which does not have a result. If you intend to block the current thread, instead of launch you may use runBlockingbuilder instead.

訳: 新しいcoroutineを作ってJob objectとしてそのcoroutineへのリファレンスを返してくれる。現在動かしているスレッドをブロックしたければrunBlockingbuilderを使うことで可能になる。

これだけで非同期処理ができるのでラクですよね。

async — This builder launches new coroutine and returns a reference to it as a Deferred type object which may have a result. It is usually used along with await which is a suspending function which can wait for a result without blocking the current thread.

訳: 新しいcoroutineを作ってDeferred typeとしてリファレンスを返す。awaitと併用されるのが通常。併用すると現在のスレッドをブロックせずに結果を待つことができる。


要はasyncを呼んでDeferredを受け取っておくと自分の好きなタイミングで後でawaitを呼ぶことで実行して結果を受け取れる、という感じです。この2つを使いこなすだけでいわゆるコールバック地獄に陥らずにすむので便利ですね!