Hello folks, i am a bit confused with the below co...
# coroutines
g
Hello folks, i am a bit confused with the below code, how come it does not print the emitted value?
Copy code
open class WrapperFlow {
    private val hotFlow = MutableSharedFlow<Int>()

    fun getFlow(): Flow<Int> = hotFlow

    @Transactional
    open suspend fun emit() {
        hotFlow.emit(10)
    }
}

suspend fun main() = coroutineScope {
    println("hi")
    val wrapperFlow = WrapperFlow()
    val job1 = launch {
        wrapperFlow.getFlow().collect {
            println("job1: $it")
        }
    }
    wrapperFlow.emit() // does not print job1: $it
    job1.cancelAndJoin()
}
Thanks in advance for any answers !
For some reason the subscriber inside launch {} does not count ?
f
You are cancelling the job before the subscriber has the chance to collect the emitted value, therefore it's not printing anything
g
if comment out the canceling, the main runs forever. The same happens if
join
instead of
cancelAndJoin()
Though, if i wrap the emitter in a launch scope it prints, In this it prints both:
Copy code
suspend fun main(): Unit = coroutineScope {
    println("hi")
    val wrapperFlow = WrapperFlow() // init flow
    val job1 = launch {
        wrapperFlow.getFlow().collect {
            println("job1: $it")
        }
    }
    println("subs: ${wrapperFlow.getFlow().subscriptionCount.value}") // 0

    launch {
        wrapperFlow.emit() // does print job1: $it
    }
    wrapperFlow.emit() // does print job1: $it
}
But like this it does not prints anything
Copy code
suspend fun main(): Unit = coroutineScope {
    println("hi")
    val wrapperFlow = WrapperFlow() // init flow
    val job1 = launch {
        wrapperFlow.getFlow().collect {
            println("job1: $it")
        }
    }
    println("subs: ${wrapperFlow.getFlow().subscriptionCount.value}") // 0

//    launch {
//        wrapperFlow.emit() // does print job1: $it
//    }
//    wrapperFlow.emit() // does print job1: $it

    wrapperFlow.emit() // does not print job1: $it if the above is commented out
}