Kotlin coroutine
Kotlinにおいてのcoroutineは軽量なthreadで実現される
が、進化して、単純なthread poolから、構造化された(CoroutineScope)実行フロー(cancelの管理)ができるようになった。
Structured concurrency - Roman Elizarov - Medium
coroutine の 中断が生じるということを意識しないと、わかってこない。
suspend (resume)を制御するのは他の言語と同じ?
中断を起こせる状況(中断を起こすために必要条件)
coroutineScopeの中でのみ。CoroutineScope#launch{} の中と、runBlocking{}の中
中断を起こせるのは、
suspendな関数を呼んだ時
withContext(){}を呼んだ時
async{}で受け取ったdefferredをawaitした時
CoroutineContext
CoroutineContext - Kotlin Programming Language
このCoroutineContextのcontextで実行される。
The coroutine context is a set of various elements. The main elements are the Job of the coroutine, which we've seen before, and its dispatcher, which is covered in this section.
jobとdispathcerで構成される要素。なので、dispatcherは何で、jobはどれということを意識すればよい。はず。
メソッドに plus, minus, fold(accumulate)があり、context要素を代数的に扱える??
jobが加算されるとは、stackに対して、積み降りするようなもの?
Understanding suspend function of Kotlin Coroutinesより
Coroutines Guide - Kotlin Programming Language
60%くらい分かってきた。もう少し。
coroutine1つに対応するthread?
threadの分類は Main, Default(worker), IOなどがあるので、coroutineのthreadは、これらのどれかと親子関係を結ぶ?
dispatherは、上記の大分類のどれに投げるかを指定する。
thread分類とは別に、名前空間による整理もあり、それが CoroutineのScope
ただ、thread分類は又ぐ事はできない。
coroutineの実体は、jobオブジェクトになる。
Job()で生成できる。
GlobalScopeという予め生成された jobもある。
Jobのメソッドで、launch, asyncがあり、これでcoroutineが動き出す。
launch, asyncは、 taskを返すので、task
kotlinx-coroutines-core
kotlinx.coroutines - kotlinx-coroutines-core
が読めるようになるのが目標
逆引き Kotlin Coroutines - Qiita
説明がわかりやすそう。最後までよめてないけど。 RxJavaとの対比で書かれてる
Dispatchersは、以下の3つがある。Main, Default, IO
メインスレッドとデフォルト(ワーカー)スレッドの振り分け
2つのAPIを順に叩く、並列で叩いて待ち合わせと、よくあるケースの紹介
GlobalScope.launch(Dispatchers.X){}
ところで、GlobalScope.launch を使う場合、生存期間はアプリ終了までになります
そのためラムダの処理が終了しない場合は、アプリの終了までインスタンスが生存し続けることになってしまいます
runBlocking{}
runBlocking は現在のスレッドをブロックするため、コルーチンとスレッドの境界でしか使用すべきではありません。
Kotlin の Coroutine を概観する - Qiitaより
Error Handling
Kotlin Coroutineの悪い例と解決策 - Qiita
val job = SupervisorJob() を使う
参考:
図で理解する Kotlin Coroutine - Qiita
Kotlin Coroutineチュートリアル - Qiita
Kotlin Coroutine の勉強経過記録 – 原理的には可能 – データ分析界隈の人のブログ、もとい雑記帳
Using Kotlin Extension Functions and Coroutines with Firebase - DEV Community 👩‍💻👨‍💻
firebaseも、referenceをget()したものをawait() すればよい? #TODO201908
How to make sense of Kotlin coroutines – ProAndroidDev
The most interesting thing is that a thread can stop executing a coroutine at some specific “suspension points”, and go do some other work. It can resume executing the coroutine later on, or another thread could even take over.
suspending functions
Kotlin Coroutinesパターン&アンチパターン - Qiita
coroutine scope
Android Coroutine coroutine