0

I created a SharedFlow, and first I added a Collector to it. Then six coroutines were started to emit data inside. Delay for a certain amount of time to ensure that the data has been emitted. cancel some coroutines. Then added a new collector.

fun main() = runBlocking {
   
    //create a sharedFlow
    val flow = MutableSharedFlow<Int>()

    //add collector 1
    launch(Dispatchers.IO) {
        flow.collect {
            log("collector_1 received $it")
            delay(3000)

        }


    }

    delay(1000)

    val job1 = launch {
        flow.emit(1)
    }
    val job2 = launch {
        flow.emit(2)
    }
    val job3 = launch {
        flow.emit(3)
    }
    val job4 = launch {
        flow.emit(4)
    }
    val job5 = launch {
        flow.emit(5)
    }
    val job6 = launch {
        flow.emit(6)
    }

    delay(1000)

    //cancel some job
    job2.cancel()
    job3.cancel()
    job4.cancel()

    delay(1000)
    launch(Dispatchers.IO) {
        flow.collect {
            log("collector_2 received $it")

        }

    }

    log("")
}

the code above only print "collector_1 received 1", then two collector suspend。 the number "5" and "6" missed . But, if we don't cancel any job, they will print correct.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
kkk
  • 141
  • 5

0 Answers0