Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pencelab/e6f4550894917dff145a7fe784c0d4b8 to your computer and use it in GitHub Desktop.
Save pencelab/e6f4550894917dff145a7fe784c0d4b8 to your computer and use it in GitHub Desktop.
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