android13/external/kotlinx.coroutines/integration/kotlinx-coroutines-jdk8
liiir1985 7f62dcda9f initial 2024-06-22 20:45:49 +08:00
..
api initial 2024-06-22 20:45:49 +08:00
src initial 2024-06-22 20:45:49 +08:00
test initial 2024-06-22 20:45:49 +08:00
README.md initial 2024-06-22 20:45:49 +08:00
build.gradle.kts initial 2024-06-22 20:45:49 +08:00

README.md

Module kotlinx-coroutines-jdk8

Integration with JDK8 CompletableFuture (Android API level 24).

Coroutine builders:

Name Result Scope Description
future CompletableFuture CoroutineScope Returns a single value with the future result

Extension functions:

Name Description
CompletionStage.await Awaits for completion of the completion stage
CompletionStage.asDeferred Converts completion stage to an instance of Deferred
Deferred.asCompletableFuture Converts a deferred value to the future

Example

Given the following functions defined in some Java API:

public CompletableFuture<Image> loadImageAsync(String name); // starts async image loading
public Image combineImages(Image image1, Image image2); // synchronously combines two images using some algorithm

We can consume this API from Kotlin coroutine to load two images and combine then asynchronously. The resulting function returns CompletableFuture<Image> for ease of use back from Java.

fun combineImagesAsync(name1: String, name2: String): CompletableFuture<Image> = future {
    val future1 = loadImageAsync(name1) // start loading first image
    val future2 = loadImageAsync(name2) // start loading second image
    combineImages(future1.await(), future2.await()) // wait for both, combine, and return result
}

Note that this module should be used only for integration with existing Java APIs based on CompletableFuture. Writing pure-Kotlin code that uses CompletableFuture is highly not recommended, since the resulting APIs based on the futures are quite error-prone. See the discussion on Asynchronous Programming Styles for details on general problems pertaining to any future-based API and keep in mind that CompletableFuture exposes a blocking method get that makes it especially bad choice for coroutine-based Kotlin code.

Package kotlinx.coroutines.future

Integration with JDK8 CompletableFuture (Android API level 24).