do other work val image = deferred.await() showImage(image) } Suspension might not happen if the result is already available processImage loadImageAsync await 1 2 processImage loadImageAsync
overlayAsync() = async(CommonPool) { val first = loadImageAsync("green") val second = loadImageAsync("red") overlay(first.await(), second.await()) } Two asynchronous computations overlayAsync overlayAsync overlayAsync
UserID): UserData fun showData(data: UserData) fun showUserInfo(cred: Credentials) { val userID = login(credentials) val userData = loadUserData(userID) showData(userData) }
Deferred<UserData> fun showData(data: UserData) fun showUserInfo(credentials: Credentials) = async(CommonPool) { val userID = login(credentials).await() val userData = loadUserData(userID).await() showData(userData) }
fun loadUserData(userID: UserID): UserData fun showData(data: UserData) suspend fun showUserInfo(credentials: Credentials) { val userID = login(credentials) val userData = loadUserData(userID) showData(userData) }
parameter: continuation Continuation is a generic callback interface: public interface Continuation<in T> { public val context: CoroutineContext public fun resume(value: T) public fun resumeWithException(exception: Throwable) }
foo() } fun fooAsync(): Single<Int> = rxSingle(CommonPool) { foo() } To call suspend foo from Java wrap it into fooAsync if you have Java 8 if you have RxJava
UserID): UserData fun showData(data: UserData) fun showUserInfo(credentials: Credentials) { val userID = login(credentials) val userData = loadUserData(userID) showData(userData) }
fun loadUserData(userID: UserID): UserData fun showData(data: UserData) suspend fun showUserInfo(credentials: Credentials) { val userID = login(credentials) val userData = loadUserData(userID) showData(userData) }