How can I pass around information from the seriali...
# serialization
c
How can I pass around information from the serialization call to the KSerializer implementation? My objects have a reference to a configuration object. The configuration object is not serialized along with them, but it is required upon deserialization. The caller of
decodeFromString()
etc functions always knows which instance should be used. How can it communicate that instance to the serializer deeper in the stack? This is specifically for the MongoDB official KxS format, which has a custom
BsonDecoder
that I can't modify.
r
For now I think the only way is to make it part of the (custom) encoder and decoder
c
Thanks for the issue, subscribing.
For now I think the only way is to make it part of the (custom) encoder and decoder
I can't, this is needed with the official MongoDB format. My own custom format already passes that information. I think I'll go with thread-locals then
o
Or rather coroutine-locals?
c
KxS isn't
suspend
, so I won't have access to those, right?
o
You can make a
ThreadLocal
become coroutine-local. And if you're using serialization from coroutines, you have to, as a coroutine can hop threads any time. You insert
Copy code
threadLocalContext.asContextElement(context)
at an appropriate (highest) point in your coroutine hierarchy, and then use
threadLocalContext
from non-suspending code (e.g. inside serialization) wherever you need it.
c
as a coroutine can hop threads any time.
Not at any time, only on suspension points, which can only happen within
suspend
functions. There are no
suspend
functions between the top-level deserialization call and the decoders.
o
Yes, if your context is short-lived and exists within a blocking section only. Then it's easier.
c
ScopedValues would be even better to avoid needing to clean it up later, but I don't think I can require such a recent JDK version
Alternative option: use
@Serializable(with = ContextualSerializer::class)
on the type, so it doesn't have a serializer at all, and register a runtime serializer in the serialization module that knows the required data?