LoginSignup
2
0

More than 5 years have passed since last update.

Kotlin 1.3のCoroutineのキャンセル③(計算処理でキャンセル可能にする)

Posted at

検証環境

この記事の内容は、以下の環境で検証しました。

  • Intellij IDEA ULTIMATE 2018.2
  • Kotlin 1.3.0
  • Gradle Projectで作成
  • GradleファイルはKotlinで記述(KotlinでDSL)

準備

詳細は下記の準備を参照してください。
https://qiita.com/naoi/items/8abf2cddfc2cb3802daa

Making computation code cancellable

前回に引き続き、公式サイトを読み解いていきます。

前回は、キャンセルの裏側の話をしました。
しかし、キャンセルできない処理についても話しました。今回のタイトルはそれをひっくり返すような感じがしますね。

早速読み進めます。

There are two approaches to making computation code cancellable. The first one is to periodically invoke a suspending function that checks for cancellation. There is a yield function that is a good choice for that purpose. The other one is to explicitly check the cancellation status. Let us try the later approach.

Replace while (i < 5) in the previous example with while (isActive) and rerun it.

意訳込みですが(略)

計算処理にキャンセル処理を実装する方法は2種類あります。1つ目は、suspend関数を定期的に呼び出し、キャンセル状態を確認する方法です。その場合は、yeil関数を呼び出すとよいでしょう。
2つ目の方法は、キャンセル状態を明示的ににチェックする方法です。isActiveを呼び出すことによりキャンセルされているか確認できます。
while(i<5)をwhile(isActive)に置き換えてみました。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0