Is it possible to add a `CoroutineContext.Element`...
# compose-web
c
Is it possible to add a
CoroutineContext.Element
inside of Compose that would get passed down to all
rememberCoroutineScope()
created by Compose?
d
If I correctly understand the question, you can pass argument to
Copy code
rememberCoroutineScope(Job() + Dispatchers.Default)
c
I mean, if you go that route, you have to specify it every time it is used. I have a custom
CoroutineContext
object that I would like automatically injected into all
rememberCoroutineScope()
call without specifying it every time
My (very limited) understanding is that Compose uses a
CoroutineScope
internally to trigger recomposition? Maybe
rememberCoroutineScope
inherits its context from there?
d
Yes, rememberCoroutineScope based on context, created inside Compose. But, I think, for now it is bot possible to add your own context to Compose hierarchy.
I think one of the possible solutions is to create your own helper functions: • Provide your own composition local property
Copy code
val MyCoroutineContext = compositionLocalOf<CoroutineContext?>
• Provide this property on top of your App
Copy code
CompositionLocalProvider(MyCoroutineContext provides Job("my additional context")) {
    //your top level Compose App
}
• Add your helper function to simpy use this providen context in amy place:
Copy code
@Composable fun rememberCoroutineScopeWithMyOwnContext():CoroutineContext {
    rememberCoroutineScope(MyCoroutineContext.current)
}
After you can use rememberCoroutineScopeWithMyOwnContext() in any place you need.
e
I’m curious @CLOVIS, why would you want to do that?
c
I have a
Auth
class that stores the user ID, to avoid having to explicitly pass it to all components in the app. As a workaround I'll just add a
withContext
in all the
ClientService
method, but I would have preferred if it were global
Other use case: adding a generic
CoroutineExceptionHandler
as a last line of defense in case someone somewhere forgot to
try-catch
in a button or something, instead of the current behavior (crashing CfW until the app is restarted)
k
@CLOVIS hey can u share this code for url like how to get bytecode from url
c
@Kapil Yadav sorry, I don't understand your question