Kotlin 1.3 で CoroutineScope

Kotlin 1.3 RC is Here: Migrate Your Coroutines! | Kotlin Blog

新しくこんなの出てます。


public interface CoroutineScope {

  /**
   * Returns `true` when this coroutine is still active (has not completed and was not cancelled yet).
   *
   * Check this property in long-running computation loops to support cancellation:
   * ```
   * while (isActive) {
   *   // do some computation
   * }
   * ```
   *
   * This property is a shortcut for `coroutineContext.isActive` in the scope when
   * [CoroutineScope] is available.
   * See [coroutineContext][kotlin.coroutines.experimental.coroutineContext],
   * [isActive][kotlinx.coroutines.experimental.isActive] and [Job.isActive].
   *
   * @suppress **Deprecated**: Deprecated in favor of top-level extension property
   */
  @Deprecated(level = DeprecationLevel.HIDDEN, message = "Deprecated in favor of top-level extension property")
  public val isActive: Boolean
    get() = coroutineContext[Job]?.isActive ?: true

  /**
   * Returns the context of this scope.
   */
  public val coroutineContext: CoroutineContext

}

新しいコルーチンのスコープです。

すべてのコルーチンビルダーは CoroutineScope の拡張となり、これを継承したコルーチンコンテキストは自動的にすべての要素にキャンセルを伝えることができます。

これを使って、アクティビティのライフサイクル周りを実装します。


class MyActivity : AppCompatActivity(), CoroutineScope {

  lateinit var job: Job

  override val coroutineContext: CoroutineContext
      get() = Dispatchers.Main + job


  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    job = Job()
  }


  override fun onDestroy() {
    super.onDestroy()

    // すべての子ジョブが destroy されたあと
    // 自動的にキャンセル
    job.cancel() 
  }


  // Activity が destroy されるか、このメソッド内で、例外が
  // 発生すると、すべてのネストしたコルーチンはキャンセルされる

  fun loadDataFromUI() = launch { // メインスレッドで起動

    val ioData = async(Dispatchers.IO) { // IOコンテキストで起動
      // ブロッキング I/O 処理
    }

    //  I/O の結果を wait
    val data = ioData.await()

    // メインスレッドで描画
    draw(data) 
  }
}

簡単な記述で、ネストしたコルーチンすべてを自動的にキャンセルしてくれるのです。

Kotlin 1.3 RC is Here: Migrate Your Coroutines! | Kotlin Blog

Using Kotlin Coroutines in your Android App


関連ワード:  AndroidKotlin速報開発