Skip to content

Instantly share code, notes, and snippets.

@rommansabbir
Last active October 16, 2023 08:54
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 rommansabbir/39a60d144ab8fa04558fefd7643d0c35 to your computer and use it in GitHub Desktop.
Save rommansabbir/39a60d144ab8fa04558fefd7643d0c35 to your computer and use it in GitHub Desktop.
Simplifying concurrency with Kotlin Coroutines : A utility function | Executes a coroutine with configurable dispatchers for subscription and observation.
/**
* Executes a coroutine with configurable dispatchers for subscription and observation.
*
* @param subscribeOn The dispatcher context for subscribing to the asynchronous operation (default: Dispatchers.IO).
* @param observeOn The dispatcher context for observing the result (default: Dispatchers.Main).
* @param block A suspend function representing the asynchronous operation to be executed.
* @param onSuccess A suspend function that is invoked with the result of the asynchronous operation when it succeeds.
* @param onError A function that is invoked if the asynchronous operation encounters an error.
*/
fun <T> withCoroutine(
subscribeOn: CoroutineContext = Dispatchers.IO,
observeOn: CoroutineContext = Dispatchers.Main,
block: suspend () -> T,
onSuccess: suspend (result: T) -> Unit,
onError: (error: Throwable) -> Unit
) {
try {
val job = Job()
CoroutineScope(subscribeOn + job).launch {
try {
val result = block()
withContext(observeOn) {
onSuccess(result)
}
} catch (e: Throwable) {
withContext(observeOn) {
onError(e)
}
} finally {
job.cancel()
}
}
} catch (e: Exception) {
onError.invoke(e)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment