Last active
October 16, 2023 08:54
-
-
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.
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
/** | |
* 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