Hi, is it possible to change the collection contex...
# coroutines
v
Hi, is it possible to change the collection context of a flow based on elements in said flow? E.g. adding a context element for downstream operators based on the current element. The naive approach violates the context preservation axioms of flows, which is why I'm not sure this is possible at all.
flowOn
obviously doesn't help: not only is it happening outside of a collection (so it doesn't see flow items), it affects the upstream, not downstream. I'm aware that one can use `channelFlow`s to switch context arbitrarily. However, this (to the best of my knowledge) doesn't affect downstream flows: there's a channel in-between that separates them. TL;DR: how do I make the flow element part of the downstream coroutine context (to propagate it through the chain of emissions) while preserving flow requirements? Is it even possible?
🚫 1
d
It looks like you're trying to recreate RxJava's behavior of the collection happening in the publisher's thread. If so, collection should happen with this dispatcher (see https://github.com/Kotlin/kotlinx.coroutines/issues/4351#issuecomment-2662769120):
Copy code
object DirectDispatcher : CoroutineDispatcher() {
    override fun dispatch(context: CoroutineContext, block: Runnable) {
        block.run()
    }
}
Then, all collection code will run in-place from the publisher. This is not idiomatic
kotlinx.coroutines
code, but it does recreate RxJava's approach to threading.
v
Hmm, ideally I'd like to still use actual coroutines rather than turning suspending into blocking code. But maybe a custom dispatcher is the way. The point is to propagate trace IDs (for telemetry) via `ThreadLocal`s (made coroutine-safe via context elements) btw. But the trace IDs are items in the flow.
d
In that case, I don't see a clean way to do that using
Flow
. The consumer of
Flow
is intentionally isolated from the context of the producer, that's by design.
v
I see. Thanks for your guidance @Dmitry Khalanskiy [JB]