dorf
07/20/2020, 11:32 PMzak.taccardi
07/20/2020, 11:32 PMoctylFractal
07/20/2020, 11:33 PMzak.taccardi
07/20/2020, 11:33 PMoctylFractal
07/20/2020, 11:34 PMcoroutineScope { ... }
zak.taccardi
07/20/2020, 11:34 PMcoroutineScope { }
to access a nested scope under the coroutine scope that called the suspending function
https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/coroutine-scope.htmlCoroutineScope
is when injecting it into a class’s constructordorf
07/20/2020, 11:35 PMasync
do I call? I suppose not the GlobalScope’szak.taccardi
07/20/2020, 11:37 PMCoroutineScope
and store it somewhere. For example on Android I would create an instance of CoroutineScope(Dispatchers.Default)
and store it in the Application
subclassdorf
07/20/2020, 11:38 PMzak.taccardi
07/20/2020, 11:38 PMApplication
as wellktor
, but is the async
you are trying to use scoped to an API call? or globally to the JVM?Application
would besuspend fun handleRequest(request: Request): Response
So you could build an object graph for any dependencies related to that call:
suspend fun handleRequest(request: Request): Response = coroutineScope {
val scope : CoroutineScope = this@coroutineScope
val graph = SomeGraphForThisApiCall(scope, otherDependencies)
}
dorf
07/20/2020, 11:53 PMGlobalScope.async
?zak.taccardi
07/20/2020, 11:53 PMGlobalScope
octylFractal
07/20/2020, 11:54 PMcoroutineScope { ... }
zak.taccardi
07/20/2020, 11:55 PMGlobalScope.async { }
will not be thrown from where you call it, unless you use .await()
on the deferred that’s returnedsuspend fun handleRequest(request: Request): Response = coroutineScope {
async {
...
}
}
octylFractal
07/20/2020, 11:58 PMasync
if you make an I/O call (or other blocking work), use withContext(<http://Dispatchers.IO|Dispatchers.IO>) { ... }
, if you suspend ktor will probably switch to handling other requests automatically, as that's what coroutines are meant to doasync
is good for is parallel processing of workdorf
07/21/2020, 12:26 AMprivate suspend fun searchAllEngines(input: String) = coroutineScope {
searchEngines.map {
async<Collection<Result>> {
try {
it.search(input)
} catch (exc: Exception) {
logger.error("${it::class.simpleName} failed: ${exc.message}")
emptyList()
}
}
}
}
octylFractal
07/21/2020, 12:34 AMit.search
is also suspend
and appropriately switches to the IO dispatcherdorf
07/21/2020, 12:39 AM