ListenableFuture を使用する

ListenableFuture は、非同期計算の結果を表します。これは、結果の生成が完了している場合と完了していない場合がある計算です。これは Future の一種で、計算が完了したとき、または計算がすでに完了している場合はすぐに実行されるコールバックを登録できます。

ListenableFuture は Android フレームワークの一部ではなく、Guava によって提供されます。このクラスの実装の詳細については、ListenableFuture の説明をご覧ください。

CameraX やヘルスサービスなど、既存の Jetpack ライブラリの多くには、戻り値の型が実行ステータスを表す ListenableFuture である非同期メソッドがあります。場合によっては、TileService の要件を満たすなど、ListenableFuture を返すメソッドを実装する必要があります。

必要なライブラリ

Groovy

dependencies {
    implementation "com.google.guava:guava:31.0.1-android"

    // To use CallbackToFutureAdapter
    implementation "androidx.concurrent:concurrent-futures:1.3.0"

    // Kotlin
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-guava:1.6.0"
}

Kotlin

dependencies {
    implementation("com.google.guava:guava:31.0.1-android")

    // To use CallbackToFutureAdapter
    implementation("androidx.concurrent:concurrent-futures:1.3.0")

    // Kotlin
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-guava:1.6.0")
}

ListenableFuture の結果を取得する

コールバックの追加

Futures.addCallback(...) ヘルパー メソッドを使用して、成功と失敗のコールバックを ListenableFuture にアタッチします。

val future: ListenableFuture<QueryResult> = ...
Futures.addCallback(
    future,
    object : FutureCallback<QueryResult> {
        override fun onSuccess(result: QueryResult) {
            // handle success.
        }

        override fun onFailure(t: Throwable) {
            // handle failure.
        }
    },
    // causes the callbacks to be executed on the main (UI) thread.
    context.mainExecutor
)

Kotlin でのサスペンド

Kotlin を使用する場合、ListenableFuture の結果を待機する最も簡単な方法は、await() を使用することです。

// import kotlinx.coroutines.guava.await

// ...

val future: ListenableFuture<QueryResult> = ...
val queryResult = future.await() // suspends awaiting success.

RxJava との相互運用

RxJava Single は、SingleEmitter 内にコールバックを登録することで、ListenableFuture から作成できます。

val future: ListenableFuture<QueryResult> = ...
val single = Single.create<QueryResult> {
    Futures.addCallback(future, object : FutureCallback<QueryResult> {
        override fun onSuccess(result: QueryResult) {
            it.onSuccess(result)
        }

        override fun onFailure(t: Throwable) {
            it.onError(t)
        }
    }, executor)
}

ListenableFuture の作成

近い将来の作成

API が非同期ではないものの、完了したオペレーションの結果を ListenableFuture にラップする必要がある場合は、ImmediateFuture を作成できます。これを行うには、Futures.immediateFuture(...) ファクトリ メソッドを使用します。

fun getResult(): ListenableFuture<QueryResult> {
    try {
        val queryResult = getQueryResult()
        return Futures.immediateFuture(queryResult)
    } catch (e: Exception) {
        return Futures.immediateFailedFuture(e)
    }
}

コルーチンを使用する

Kotlin では、future{ ... } を使用して、suspend 関数の結果を ListenableFuture に変換できます。

// import kotlinx.coroutines.guava.future

suspend fun getResultAsync(): QueryResult = /* ... */

fun getResultFuture(): ListenableFuture<QueryResult> {
    return coroutineScope.future {
        getResultAsync()
    }
}

コールバックの変換

コールバック ベースの API を ListenableFuture を使用する API に変換するには、CallbackToFutureAdapter を使用します。この API は androidx.concurrent:concurrent-futures アーティファクトによって提供されます。

詳細については、androidx.concurrent をご覧ください。

RxJava Single からの変換

RxJava を使用する場合、Single を SettableFuture に変換できます。これは ListenableFuture を実装します。

fun getResult(): ListenableFuture<QueryResult> {
    val single: Single<QueryResult> = ...

    val future = SettableFuture.create<QueryResult>()
    single.subscribe(future::set, future::setException)
    return future
}