Stefan Oltmann
02/03/2022, 2:04 PMtask
is always on the main thread.
Task.detached
starts a new task on another thread.
The problem is Task.detached()
runs to completion even is task is cancelled because the cancellation is not propagated.
Can some expert please enlight me how to correctly do that?
.task {
Task.detached {
guard image == nil else { return }
image = await imageLoader.loadThumbnailImage(photoUri: photo.uri)
}
}
hfhbd
02/03/2022, 2:07 PM.task(priority: .background) {
Task {
}
}
Stefan Oltmann
02/03/2022, 2:09 PMhfhbd
02/03/2022, 2:16 PMTask.detached
is GlobalScope
, which doesn't inherit cancelation too:
suspend fun a() {
while (true) {
delay(1.seconds)
println("Still running")
}
}
@OptIn(DelicateCoroutinesApi::class)
@Test
fun b(): Unit = runBlocking {
withTimeout(5.seconds) {
GlobalScope.launch {
a()
}
}
delay(10.seconds)
}
Stefan Oltmann
02/03/2022, 2:24 PMwithContext()
equivalent in Swift?hfhbd
02/03/2022, 2:37 PMimport SwiftUI
struct ContentView: View {
let a = A()
var body: some View {
Text("Hello, world!")
.padding()
.task(priority: .background) {
print("Start Thread")
await a.a()
}
}
}
actor A {
func a() async {
Task {
print("Start Sleeping")
try await Task.sleep(nanoseconds: 50_000_000_000)
}
}
}
Stefan Oltmann
02/03/2022, 2:47 PMhfhbd
02/03/2022, 2:50 PMasync
calls sequentiell!Stefan Oltmann
02/03/2022, 2:50 PMhfhbd
02/03/2022, 3:47 PM