Skip to content

Publisher.asFlow() sometimes fails to propagate thread context elements #4422

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
dkhalanskyjb opened this issue Apr 23, 2025 · 0 comments
Open

Comments

@dkhalanskyjb
Copy link
Collaborator

This issue was discovered analytically, by reading the source code. No one reported it yet.

val threadLocal = ThreadLocal<String>.withInitial { "default" }

@Test
fun testFlowOnThreadContext() = runBlocking {
    val publisher = Publisher<Int> { it ->
        it.onSubscribe(object : Subscription {
            override fun request(n: Long) {
                assertEquals("value", threadLocal.get())
                it.onNext(1)
                it.onComplete()
            }

            override fun cancel() {}
        })
    }

    val context1 = Dispatchers.IO + threadLocal.asContextElement("value")
    val context2 = threadLocal.asContextElement("value")

    // succeeds
    publisher.asFlow().flowOn(context1).collect { }
    // fails with org.junit.ComparisonFailure: expected:<[value]> but was:<[default]>
    publisher.asFlow().flowOn(context2).collect { }
}
dkhalanskyjb added a commit that referenced this issue May 6, 2025
Fixes #4422
and several other undiscovered problems.
dkhalanskyjb added a commit that referenced this issue May 21, 2025
Fixes #4403
Fixes #4422
Fixes some other, similar bugs that weren't reported.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant