1 /*
<lambda>null2 * 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
19 package androidx.work
20
21 import androidx.concurrent.futures.CallbackToFutureAdapter.getFuture
22 import com.google.common.util.concurrent.ListenableFuture
23 import java.util.concurrent.Executor
24 import java.util.concurrent.atomic.AtomicBoolean
25 import kotlin.coroutines.CoroutineContext
26 import kotlin.coroutines.EmptyCoroutineContext
27 import kotlinx.coroutines.CancellationException
28 import kotlinx.coroutines.CoroutineScope
29 import kotlinx.coroutines.CoroutineStart
30 import kotlinx.coroutines.Job
31 import kotlinx.coroutines.launch
32
33 internal fun <T> launchFuture(
34 context: CoroutineContext = EmptyCoroutineContext,
35 start: CoroutineStart = CoroutineStart.DEFAULT,
36 block: suspend CoroutineScope.() -> T,
37 ): ListenableFuture<T> = getFuture { completer ->
38 val job = context[Job]
39 completer.addCancellationListener({ job?.cancel() }, DirectExecutor.INSTANCE)
40 CoroutineScope(context).launch(start = start) {
41 try {
42 val result = block()
43 completer.set(result)
44 } catch (_: CancellationException) {
45 completer.setCancelled()
46 } catch (throwable: Throwable) {
47 completer.setException(throwable)
48 }
49 }
50 }
51
executeAsyncnull52 internal fun <V> Executor.executeAsync(debugTag: String, block: () -> V): ListenableFuture<V> =
53 getFuture { completer ->
54 val cancelled = AtomicBoolean(false)
55 completer.addCancellationListener({ cancelled.set(true) }, DirectExecutor.INSTANCE)
56 execute {
57 if (cancelled.get()) return@execute
58 try {
59 completer.set(block())
60 } catch (throwable: Throwable) {
61 completer.setException(throwable)
62 }
63 }
64 debugTag
65 }
66