privatefunupdateState(expectedState: Any?, newState: Any): Boolean { synchronized(this) { val oldState = _state.value if (expectedState != null && oldState != expectedState) returnfalse// 1 CAS support if (oldState == newState) returntrue// 2 Don't do anything if value is not changing, but CAS -> true _state.value = newState }
// MutableStateFlow(initialValue) is a shared flow with the following parameters: val shared = MutableSharedFlow( replay = 1, extraBufferCapacity = 0, onBufferOverflow = BufferOverflow.DROP_OLDEST ) shared.tryEmit(initialValue) // emit the initial value val state = shared.distinctUntilChanged() // get StateFlow-like behavior, 这一步就相当于加上了 equality判断功能