Last active
October 30, 2019 23:25
-
-
Save pencelab/e6f4550894917dff145a7fe784c0d4b8 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
class Operator: CoroutineScope { | |
companion object { | |
const val OPERATION_IS_EVEN = "Operation [Is Even]" | |
const val OPERATION_AVERAGE = "Operation [Average]" | |
const val OPERATION_SQUARE = "Operation [Square]" | |
} | |
private val job = SupervisorJob() | |
private val exceptionHandler = CoroutineExceptionHandler { _, exception -> | |
log("Exception Handler Caught: [ $exception ] with suppressed ${exception.suppressed.contentToString()}") | |
} | |
override val coroutineContext: CoroutineContext | |
get() = job + Dispatchers.Default + exceptionHandler | |
private suspend fun myRandomNumberSuccess(operation: String): Int = withContext(Dispatchers.Default) { | |
log("$operation Retrieving random number...") | |
delay(2000) //Simulating a heavy computation | |
val random = (1..100).random() | |
log("$operation Random Number = $random") | |
random | |
} | |
private suspend fun myRandomNumberFail(operation: String): Int = withContext(Dispatchers.Default) { | |
log("$operation Retrieving random number...") | |
delay(1000) //Simulating a heavy computation | |
throw IllegalStateException("$operation Retrieving random number failed.") | |
} | |
fun release() { | |
this.job.cancel() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment