https://kotlinlang.org logo
Title
u

ursus

12/03/2021, 1:08 AM
do I need to cancel my coroutine scopes in tests if it seems the test process gets killed? or does it?
n

Nick Allen

12/03/2021, 2:24 AM
Not really sure what you mean. Do you have a simple repro that demonstrates the issue?
u

ursus

12/03/2021, 3:13 AM
@Test 
fun foo() {
	GlobalScope.launch {
		intervalFlow(10)
	        .collect {
	            log("---- INTERVAL=$it")
	        }
    }
}
why does the flow stops, it should continue for ever, i.e. a leak, right?
n

Nick Allen

12/03/2021, 3:16 AM
coroutines are not threads, they will not keep your process alive.
The thread running
foo()
returns right away (
launch
starts the coroutine but then returns immediately). Once it's done, process ends.
If you want the process to live on, then you need to force a non-daemon thread to wait:
@Test 
fun foo() {
	runBlocking { //This blocks test thread
		intervalFlow(10)
	        .collect {
	            log("---- INTERVAL=$it")
	        }
    }
}
u

ursus

12/03/2021, 1:12 PM
I dont want it to wait, im just studying how it works. Also, if I do pure thread it stops.. which means I think it got gced, since other tests run afterwards, so I assume the process didnt get killed per test
n

Nick Allen

12/04/2021, 12:27 AM
Non-daemon threads are GC roots. They can't be GC'd and the process will never exit while one is still running.
I haven't come across a unit testing framework that creates a process for each test execution. This means that any threads or coroutines you create in one test could still be running when other tests run if you don't clean up and wait for them.
u

ursus

12/04/2021, 2:36 AM
that makes sense, but they dont, printlns stop