Last active
April 4, 2018 06:36
-
-
Save adamw/9b829907f89c95bafc39f46ab0fcc903 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package test | |
| import kotlinx.coroutines.experimental.Deferred | |
| import kotlinx.coroutines.experimental.async | |
| import test.Compare4Synchronous.ProfileData | |
| import test.Compare4Synchronous.User | |
| import kotlin.reflect.KClass | |
| fun compare4() { | |
| // I/O operations: non-blocking, asynchronous | |
| fun <T: Any> fetchFromDb(entityClass: KClass<T>, id: Long): Deferred<T?> { | |
| throw UnsupportedOperationException() } | |
| fun sendEmail(to: String?, content: String): Deferred<Void> { | |
| throw UnsupportedOperationException() } | |
| fun sendHttpPost(url: String, payload: Any): Deferred<Void> { | |
| throw UnsupportedOperationException() } | |
| // the bussines logic: asynchronous | |
| fun runBusinessProcess(profileData: ProfileData): Deferred<String> { | |
| // async {} delimits coroutine code where .await() can be called | |
| // the result of an async {} block is a Deferred<> value | |
| return async { | |
| // await() is only allowed inside suspendable functions | |
| // and async {} blocks. It looks like synchronous, blocking | |
| // code, but behind the scenes is compiled into a non-blocking | |
| // version | |
| val user = fetchFromDb(User::class, profileData.userId).await() | |
| if (user != null) { | |
| sendHttpPost("http://profile_service/post/" + | |
| profileData.userId, profileData).await() | |
| if (user.notificationsEnabled) { | |
| sendEmail(user.email, "profile updated").await() | |
| } | |
| "ok" | |
| } else { | |
| "user not found" | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment