How can I store "contextual" data (associated with...
# javascript
n
How can I store "contextual" data (associated with a single chain of function calls) in Kotlin/Javascript in the browser? In Kotlin/Java I use
ThreadLocal
and
ThreadContextElement
but I struggle to find a good alternative in Kotlin/Javascript. As usual, I started to make all of my functions
suspend
(because it is "viral" anyway) but if I call a
non-suspend
library function the context is lost. Thanks.
r
JS is single-threaded. The whole app is just single chain of function calls 😉
n
I know :] But maybe you know what I mean, like a Javascript alternative to MDC in logging? Is the only solution to pass around info in function parameters?
r
As there is always one thread, I think you can just use a global variable instead of
ThreadLocal
.
Initialize your context in some place, put it in the variable and it will be valid until some new part of code is executed where some other context is initialized and saved.
But it could probably work with non-suspend functions only.
n
It know it is single-threaded but there are multiple task running at the same time. Like one task is updating the UI, some other is making a network call and waiting for the result, another is waiting for a timer to expire. These are separate "threads of execution", and I would like to find a solution to implement for example MDC in logging. (I know this is a theoretical question but I'm curious what are the alternatives besides passing the info in parameters -
suspend
functions do this as well, they pass the continuation as a parameter.)
e
You can associate data using coroutine scopes if I'm not mistaken. I don't recall the details, but in case ask in #coroutines
👍🏻 1
@Norbi curious if you managed to find a reasonable approach
n
I already use
CoroutineContext
and it's OK for me because my app is Kotlin-only. I was just curious that JS really doesn't have an alternative built-in solution. I have read about: • _async_hooks_ (node.js-specific) • https://www.npmjs.com/package/zone.jshttps://github.com/vlcn-io/model/tree/main/ts/packages/zone
thank you color 1