You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

kotlin.adoc 1.5KB

123456789101112131415161718192021222324252627282930313233
  1. ---
  2. title: "Kotlin"
  3. ---
  4. == Kotlin
  5. === Assorted coroutine notes
  6. * *launched* in the context of a scope, e.g. `GlobalScope`
  7. * `launch` and `runBlocking` are both builders
  8. ** Can parameterise `runBlocking` for e.g. tests - `runBlocking<Unit> {...}`
  9. ** Builders return a job, can call `job.join()` to wait, `job.cancel()` to stop
  10. ** Every builder adds a `CoroutineScope` to the scope of a code block
  11. ** `launch`/`runBlocking` operate on current scope
  12. * `coroutineScope` is a builder to manually create a scope
  13. * `suspend` functions don't carry the scope
  14. ** keep a reference in the class/fun
  15. ** make them an extension method on CoroutineScope
  16. * Coroutines launched in `GlobalScope` don't keep the process alive if `main()` returns
  17. * Cancellation is co-operative - must throw `CancellationException`
  18. ** Can check `isAlive` property
  19. ** `withContext(NonCancellable)` if job *can't* be cancelled (e.g. suspend fun in a finally block)
  20. * `withTimeout` and `withTimeoutOrNull` cancel automatically
  21. * Children can be cancelled with `coroutineContext.cancelChildren()`
  22. * `async` is like `launch` but returns a `Deferred`
  23. * Contexts are job + dispatcher
  24. * Dispatcher specifies thread to run on
  25. * Launchers take an optional context
  26. ** `launch(newSingleThreadContext("name")) {...}`
  27. * `GlobalScope`'s dispatcher uses a shared threadpool
  28. * Can get own job from `CoroutineContext[Job]`
  29. * `CoroutineName` gives named context
  30. ** Can concat contexts with `+`
  31. * `select` can receive data from multiple channels, like Go