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