【发布时间】:2025-12-25 21:00:07
【问题描述】:
如果我在启动时使用while循环,它会一直运行,点击事件不会执行,最终导致ANR。 StateFlowImpl collect 有一个while循环,什么时候退出循环,这是我的情况:
class MainActivity : AppCompatActivity(), CoroutineScope by MainScope() {
private val TAG = "MainActivity"
val flow = MutableStateFlow(0)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
launch {
while (true) {
Log.d(TAG, "while")
}
}
launch {
flow.collect {
Log.d(TAG, "onCreate: $it")
}
}
}
}
// This is StateFlowImpl
override suspend fun collect(collector: FlowCollector<T>) {
val slot = allocateSlot()
try {
if (collector is SubscribedFlowCollector) collector.onSubscription()
val collectorJob = currentCoroutineContext()[Job]
var oldState: Any? = null // previously emitted T!! | NULL (null -- nothing emitted yet)
while (true) {
val newState = _state.value
collectorJob?.ensureActive()
if (oldState == null || oldState != newState) {
collector.emit(NULL.unbox(newState))
oldState = newState
}
if (!slot.takePending()) {
slot.awaitPending()
}
}
} finally {
freeSlot(slot)
}
}
【问题讨论】: