Question about flows

So I was playing around with flows and have something like this here:

suspend fun main() { var counter = 2 val mutex = Mutex() val flow = flow<Int> { emit(1) emit(11) emit(111) while (true) { delay(1000) mutex.withLock { emit(counter) counter++ } } } withContext(Dispatchers.Default) { launch { flow.collect { value -> println("collect 1: $value") } } launch { flow.collect { value -> println("collect 2: $value") } } launch { flow.collectLatest { value -> println("collect 3: $value") } } delay(5000) launch { flow.collect { value -> println("collect 4: $value") } } } } 

The output looks something like this:

collect 1: 1 collect 2: 1 collect 1: 11 collect 2: 11 collect 1: 111 collect 2: 111 collect 3: 1 collect 3: 11 collect 3: 111 collect 1: 2 collect 2: 3 collect 3: 4 collect 1: 5 collect 2: 6 collect 3: 7 collect 1: 8 collect 2: 9 collect 3: 10 collect 1: 11 collect 2: 12 collect 3: 13 collect 4: 1 collect 4: 11 collect 4: 111 collect 1: 14 collect 2: 15 collect 3: 16 collect 4: 17 collect 1: 18 collect 2: 19 collect 3: 20 collect 4: 21 collect 1: 22 collect 2: 23 collect 3: 24 collect 4: 25 collect 1: 26 collect 2: 27 collect 3: 28 collect 4: 29 

I was wondering why collect 4 doesn’t also print out all subsequent emitted numbers, but only the numbers 1, 11, 111?

I was expecting to see something like this:

collect 4: 1 collect 4: 11 collect 4: 111 collect 4: 2 collect 4: 3 collect 4: 4 collect 4: 5 and so on until it reaches the current counter number. 

submitted by /u/IllTryToReadComments
[link] [comments]