For an Android project, you would want to add a dependency on org.jetbrains.kotlinx:kotlinx-coroutines-android. This has transitive dependencies to pull in the core coroutines code, plus it has Android-specific elements.
b4777467766citeerde uit2 jaar geleden
Primarily, a CoroutineScope is responsible for canceling and cleaning up coroutines when the CoroutineScope is no longer needed. GlobalScope will be set up to support the longest practical lifetime: the lifetime of the process that is running the Kotlin code.
b4777467766citeerde uit2 jaar geleden
Part of the configuration that you can provide to a coroutine builder is a dispatcher. This indicates what thread pool (or similar structure) should be used for executing the code inside of the coroutine.
b4777467766citeerde uit2 jaar geleden
By default, a coroutine builder will use Dispatchers.Default, though that default can be overridden in different circumstances, such as in different implementations of CoroutineScope.
b4777467766citeerde uit2 jaar geleden
we can mark functions with the suspend keyword. This tells the coroutines system (particularly the current dispatcher) that it is OK to suspend execution of the current block of code and to feel free to run other code from another coroutine builder if there is any such code to run.
b4777467766citeerde uit2 jaar geleden
Our stallForTime() function has the suspend keyword. So, when Kotlin starts executing the code that we provided to launch(), when it comes time to call stallForTime(), Kotlin could elect to execute other coroutines scheduled for Dispatchers.Main.
b4777467766citeerde uit2 jaar geleden
As the name suggests, a CoroutineContext provides a context for executing a coroutine.
b4777467766citeerde uit2 jaar geleden
withContext() takes a different block of code and executes it with a modified CoroutineContext.
b4777467766citeerde uit2 jaar geleden
Little production code is used directly from a main() function. And your choice of coroutine scope and coroutine builder are fairly important concepts. So, while the suspend main() approach works, you will not see it used much here.
b4777467766citeerde uit2 jaar geleden
So, while within a single coroutine, all statements are sequential, multiple coroutines for the same dispatcher can be executed concurrently. Kotlin can switch between coroutines when it encounters a suspend function.
fb2epub
Sleep je bestanden hiernaartoe
(maximaal 5 per keer)