Skip to content

Instantly share code, notes, and snippets.

@adamw
Last active April 4, 2018 06:36
Show Gist options
  • Select an option

  • Save adamw/9b829907f89c95bafc39f46ab0fcc903 to your computer and use it in GitHub Desktop.

Select an option

Save adamw/9b829907f89c95bafc39f46ab0fcc903 to your computer and use it in GitHub Desktop.
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