Worker
Worker presents a unified API across all platforms to interact with threads. A Worker can execute a job in its event loop. If needed, it can also resume the flow on a different worker instance. All threads including main
are exposed via this API. For example, to get a Worker backed by main
thread, use WorkerFactory.main.
A worker job
must satisfy the following requirements:
The
job
must be a non state capturing lambda which does not capture any outside state.Any input required by the
job
must be passed before hand in the execute or executeAndResume methodjobInput
parameters.The
job
input arguments must be treated as immutable to guarantee thread safety.
The basic idea behind worker is to bring the same level of abstraction to every platform as Native has because native concurrency is the most restrictive one.
On iOS, it uses the Kotlin/Native's Worker
API. On Android, it uses Handler
.
Examples
Run job on background Worker
val worker = WorkerFactory.newBackgroundThread()
// calling execute schedules a task on worker
val future = worker.execute("Hello") {it: String ->
assertEquals("Hello", it)
"World"
}
// wait for worker to complete, use await
val result: String = future.await()
assertEquals("World", result)
Resume job on a different Worker
val worker1 = WorkerFactory.newBackgroundWorker()
val worker2 = WorkerFactory.newBackgroundWorker()
val future = worker2.executeAndResume(INPUT, {
assertEquals(INPUT, it)
OUTPUT
}, worker1, true) {
assertEquals(OUTPUT, it)
it
}
assertEquals(OUTPUT, future.await())
Resume Job on main worker
val worker = WorkerFactory.newBackgroundWorker()
val future = worker.executeAndResume(INPUT, {
assertEquals(INPUT, it)
OUTPUT
}, awaitResumingJob = true) {
// called on main thread asynchronously
assertEquals(OUTPUT, it)
it
}
// do not call future.await because it will block main thread.