Created
May 14, 2023 14:52
-
-
Save omkar-tenkale/7f458e33b09a62183308c39fc7d8db46 to your computer and use it in GitHub Desktop.
This file contains 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
import kotlin.concurrent.thread | |
import kotlin.coroutines.Continuation | |
import kotlin.coroutines.CoroutineContext | |
import kotlin.coroutines.EmptyCoroutineContext | |
import kotlin.coroutines.intrinsics.createCoroutineUnintercepted | |
import kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn | |
import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED | |
fun main() { | |
// Define a suspend lambda | |
val suspendingLambda: suspend () -> Double = suspend { | |
calculateFourthRoot(16.0) | |
} | |
// Define a callback object | |
val completionCallback = object : Continuation<Double> { | |
override val context: CoroutineContext = EmptyCoroutineContext | |
override fun resumeWith(result: Result<Double>) { | |
// Prints ④ 2.0 | |
println("④ ${result.getOrNull()}") | |
} | |
} | |
// Create the coroutine | |
val continuation = suspendingLambda.createCoroutineUnintercepted(completionCallback) | |
// Start the coroutine | |
continuation.resumeWith(Result.success(Unit)) | |
} | |
// The fourth root is the square root of a square root | |
suspend fun calculateFourthRoot(number: Double): Double { | |
var current = number | |
println("① $current") // Prints ① 16.0 | |
current = calculateSquareRoot(current) | |
println("② $current") // Prints ② 4.0 | |
current = calculateSquareRoot(current) | |
println("③ $current") // Prints ③ 2.0 | |
return current | |
} | |
suspend fun calculateSquareRoot(number: Double): Double { | |
val block: (Continuation<Double>) -> Any? = { | |
// Do heavy calculation in background thread | |
thread { | |
val sqrt = kotlin.math.sqrt(number) | |
it.resumeWith(Result.success(sqrt)) | |
} | |
COROUTINE_SUSPENDED | |
} | |
return suspendCoroutineUninterceptedOrReturn(block) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment