Hi, I'm seeing a strange behaviour when I use Ktor...
# ktor
s
Hi, I'm seeing a strange behaviour when I use Ktor in development mode. If I collect a cold flow in a coroutine launched using
Application
as the scope, the flow always encounters a context preservation error. The error disappears if I turn off development mode. Simple reproducible example:
Copy code
fun Application.module() {
    configureRouting()

    launch {
        flow {
            emit(1)
            emit(2)
            emit(3)
        }.collect {
            println("Collected: $it")
        }
    }
}
with
application.yaml
Copy code
ktor:
    application:
        modules:
            - com.example.ApplicationKt.module
    deployment:
        port: 8080
    development: true
The error I receive is
Copy code
Exception in thread "main" java.lang.IllegalStateException: Flow invariant is violated:
		Flow was collected in [StandaloneCoroutine{Active}@64c2b546, io.ktor.server.application.ClassLoaderAwareContinuationInterceptor@7e094740],
		but emission happened in [StandaloneCoroutine{Active}@64c2b546, io.ktor.server.application.ClassLoaderAwareContinuationInterceptor@7e094740].
		Please refer to 'flow' documentation or use 'flowOn' instead
	at kotlinx.coroutines.flow.internal.SafeCollector_commonKt.checkContext(SafeCollector.common.kt:84)
	at kotlinx.coroutines.flow.internal.SafeCollector.checkContext(SafeCollector.kt:132)
	at kotlinx.coroutines.flow.internal.SafeCollector.emit(SafeCollector.kt:109)
	at kotlinx.coroutines.flow.internal.SafeCollector.emit(SafeCollector.kt:82)
	at com.example.ApplicationKt$module$1$1.invokeSuspend(Application.kt:19)
	at com.example.ApplicationKt$module$1$1.invoke(Application.kt)
a
This is most likely one of the variations of the KTOR-4843. Unfortunately, the only workaround I know of is to disable the development mode.
👍 1