ribesg
01/23/2020, 10:12 AMdispatch_async
call returning a result? i.e. how to bridge coroutines and multithreading as coroutines themselves can’t run outside of main threadribesg
01/23/2020, 10:31 AMactual suspend fun <T> runAsync(task: () -> T): T {
var result: Result<T>? = null
@Suppress("EXPERIMENTAL_UNSIGNED_LITERALS")
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
result = try {
Result.success(task())
} catch (t: Throwable) {
Result.failure(t)
}
}
while (result == null) delay(10)
return (result as Result<T>).getOrThrow()
}
ribesg
01/23/2020, 10:36 AMbasher
01/23/2020, 3:40 PMribesg
01/23/2020, 3:49 PMInvalidMutabilityException: mutation attempt of frozen kotlinx.coroutines.DispatchedContinuation
ribesg
01/23/2020, 3:51 PMribesg
01/23/2020, 3:51 PMactual suspend fun <T> runAsync(task: CoroutineScope.() -> T): T =
threadSafeSuspendCallback<T> { completion ->
val job = CoroutineWorker.execute {
val result = runCatching { task() }
completion(result)
}
return@threadSafeSuspendCallback { job.cancel() }
}
ribesg
01/23/2020, 3:55 PMUncaught Kotlin exception: kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen com.autodesk.coroutineworker.$waitAndDelayForConditionCOROUTINE$165@16207c8
basher
01/23/2020, 4:47 PMactual suspend fun <T> runAsync(task: CoroutineScope.() -> T): T =
CoroutineWorker.withContext {
task()
}
ribesg
01/24/2020, 9:14 AMribesg
01/24/2020, 9:24 AMbasher
01/24/2020, 1:41 PMribesg
01/24/2020, 2:01 PMEmptyCoroutineContext
basher
01/24/2020, 2:30 PMribesg
01/24/2020, 3:09 PMtask
can’t just capture anything like that, that’s why I got all those errors. I now have moved to a more “actual worker” solution with CoroutineWorker.execute
and a collection from Stately to pass data to it.
What do you mean by “just executing task”? I want it to run on another thread as it’s something that could basically block the thread for some millisecondsbasher
01/24/2020, 5:41 PMtask()
. you're already in a suspend
context. it depends though if you think task
is actually going to block the current threadbasher
01/24/2020, 5:42 PMwithContext
is useful in cases where you'd want to do withContext(<http://Dispiatcher.IO|Dispiatcher.IO>)
on JVMribesg
01/25/2020, 2:52 PMtask
on another thread. Just running task()
can never do that