非同期処理には必ず絡んでくるのがライフサイクル。
RxJava のようにまとめたいですよね。
private CompositeDisposable compositeDisposable =
new CompositeDisposable();
@Override public void onCreate() {
compositeDisposable.add(backendApi.loadUser()
.subscribe(this::displayUser, this::handleError));
}
@Override public void onDestroy() {
compositeDisposable.clear();
}
SendChannel を使って同様にこのような。
interface JobHolder {
val job: Job
}
class MainActivity : AppCompatActivity(), JobHolder {
override val job: Job = Job()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
addJob {
while (true) {
delay(500)
println("A")
}
}
addJob {
while (true) {
delay(1000)
println("B")
}
}
}
// Job の actor として action を登録する
private fun addJob(action: suspend () -> Unit) {
val actor = actor<Unit>(job + UI, capacity = Channel.CONFLATED) {
for (event in channel) action()
}
actor.offer(Unit)
}
override fun onDestroy() {
super.onDestroy()
job.cancel()
}
}
まとめてキャンセルできましたね!
どうせなら作って置いたらどうだろう。
class JobHolder {
private val job = Job()
fun add(action: suspend () -> Unit) {
val actor = actor<Unit>(job + UI, capacity = Channel.CONFLATED) {
for (event in channel) action()
}
actor.offer(Unit)
}
fun cancel() {
job.cancel()
}
}
Lifecycle and coroutine parent-child hierarchy
Children of a coroutine
こうでもいけるってよ: 2018-04-27追記
val rootParent = Job()
fun foo() {
launch(UI, parent = rootParent) {
// ...
}
}
fun bar() {
launch(CommonPool, parent = rootParent) {
// ...
}
}
fun destroy() { rootParent.cancel() }
Kotlin Coroutines on Android: Things I Wish I Knew at the Beginning