Created
August 5, 2019 06:05
-
-
Save arnyigor/a7a039d4addcc83ebee117e79c9da515 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 kotlinx.coroutines.* | |
import kotlin.coroutines.CoroutineContext | |
fun <T> launchAsync(block: suspend () -> T, onComplete: (T) -> Unit = {}, onError: (Throwable) -> Unit = {}, dispatcher: CoroutineDispatcher = Dispatchers.IO, context: CoroutineContext = Dispatchers.Main + SupervisorJob(), onCanceled: () -> Unit = {}): Job { | |
val scope = CoroutineScope(context) | |
return scope.launch { | |
try { | |
val result = withContext(dispatcher) { block.invoke() } | |
onComplete.invoke(result) | |
} catch (e: CancellationException) { | |
onCanceled() | |
} catch (e: Exception) { | |
onError(e) | |
} | |
} | |
} | |
fun Job.addTo(compositeJob: CompositeJob) { | |
compositeJob.add(this) | |
} | |
fun <T> CoroutineScope.launch(block: suspend () -> T, onError: (Throwable) -> Unit? = {}, onCanceled: () -> Unit? = {}): Job { | |
return this.launch { | |
try { | |
block.invoke() | |
} catch (e: CancellationException) { | |
onCanceled() | |
} catch (e: Exception) { | |
onError(e) | |
} | |
} | |
} | |
fun getMainScope(): CoroutineScope { | |
return CoroutineScope(Dispatchers.Main + SupervisorJob()) | |
} | |
suspend fun <T> async(block: suspend () -> T): T { | |
return withContext(Dispatchers.IO) { block.invoke() } | |
} | |
fun <T> launch(block: suspend () -> T): CoroutineScope { | |
val scope = CoroutineScope(Dispatchers.Main + SupervisorJob()) | |
scope.launch { block.invoke() } | |
return scope | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment