Refer to following codes:
@Test
fun test() = runBlocking {
val tag = testName.methodName
var mutFlow = MutableStateFlow(mutableListOf<Int>())
val imFlow = mutFlow.asStateFlow()
Log.d(tag, "mutable value is ${imFlow.value}")
val job = launch {
imFlow.collect {
Log.d(tag, "job1 collected value is $it @${System.identityHashCode(it)}")
it.add(100)
}
}
repeat (5) {
val a = mutFlow.value
a.add(it)
mutFlow.value = a
delay(1)
}
delay(10)
Log.d(tag, "mutable value is ${imFlow.value}")
job.cancelAndJoin()
}
Two questions:
- Is it thread safy to modify a mutable variable in producer and consumer concurrently?
- Why consumer just got one collect callback?
This is the log:
D test: mutable value is []
D test: job1 collected value is [0] @153163998
D test: mutable value is [0, 100, 1, 2, 3, 4]