blob: 51504ab58199c51152eeaf217bd846827cc31374 [file] [log] [blame]
Dustin Lam60c79052019-11-01 13:43:57 -07001/*
2 * Copyright 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17@file:Suppress("NOTHING_TO_INLINE")
18
19package androidx.work
20
21import androidx.annotation.RestrictTo
22import com.google.common.util.concurrent.ListenableFuture
23import kotlinx.coroutines.suspendCancellableCoroutine
24import java.util.concurrent.CancellationException
25import java.util.concurrent.ExecutionException
26import kotlin.coroutines.resume
27import kotlin.coroutines.resumeWithException
28
29/**
30 * Awaits for the completion of the [ListenableFuture] without blocking a thread.
31 *
32 * @return R The result from the [ListenableFuture]
33 *
34 * @hide
35 */
36@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
37suspend inline fun <R> ListenableFuture<R>.await(): R {
38 // Fast path
39 if (isDone) {
40 try {
41 return get()
42 } catch (e: ExecutionException) {
43 throw e.cause ?: e
44 }
45 }
46 return suspendCancellableCoroutine { cancellableContinuation ->
47 addListener(Runnable {
48 try {
49 cancellableContinuation.resume(get())
50 } catch (throwable: Throwable) {
51 val cause = throwable.cause ?: throwable
52 when (throwable) {
53 is CancellationException -> cancellableContinuation.cancel(cause)
54 else -> cancellableContinuation.resumeWithException(cause)
55 }
56 }
57 }, DirectExecutor.INSTANCE)
58 }
59}