前言
在之前的文章已經分析了SharedFlow原理,在這個基礎上再來分析StateFlow就簡單多了。Kotlin SharedFlow 源碼解析
StateFlow使用與特性分析
如下代碼,創建了一個StateFlow對象,必須有個初始值,這里設置為1。發射了3條數據,但是收集者只收到value為3的這條數據。
runBlocking {
val stateFlow = MutableStateFlow(1)
stateFlow.value = 2
stateFlow.value = 3
stateFlow.value = 3
launch {
stateFlow.collect {
delay(3000)
print("collect2 :$it")
}
}
}
StateFlow最新的收集者只能收到最新的1條數據;如果數據相同,不會收到重復的數據。StateFlow可以看作如下定義的ShareFlow。
MutableSharedFlow<Int>(replay = 1, extraBufferCapacity = 0, onBufferOverflow = BufferOverflow.DROP_OLDEST)
StateFlow源碼分析
初始化
public fun <T> MutableStateFlow(value: T): MutableStateFlow<T> = StateFlowImpl(value ?: NULL)
StateFlow
并沒有像SharedFlow
那樣采用緩存數組,只是用atomic引用類型的狀態值,來保存最新的值。
private class StateFlowImpl<T>(
initialState: Any
) : AbstractSharedFlow<StateFlowSlot>(), MutableStateFlow<T>, CancellableFlow<T>, FusibleFlow<T> {
private val _state = atomic(initialState) // 保存狀態值
private var sequence = 0 // 狀態值更新的序列號
@Suppress("UNCHECKED_CAST")
public override var value: T
get() = NULL.unbox(_state.value)
set(value) { updateState(null, value ?: NULL) } //CAS方式更新數據
override fun compareAndSet(expect: T, update: T): Boolean =
updateState(expect ?: NULL, update ?: NULL)
}
在StateFlow中一般有3種方式發射數據,emit
、setValue
,compareAndSet
,但是無論哪種方式最終都是調用updateState
方法,所以我們直接看這個方法就好。
發射數據
private fun updateState(expectedState: Any?, newState: Any): Boolean {
var curSequence = 0
var curSlots: Array<StateFlowSlot?>? = this.slots // benign race, we will not use it
synchronized(this) {
val oldState = _state.value
//看過CAS原理的同學能很好理解這句話的意思,內存值和預期值不同,直接返回false;說明是線程安全的,內存值和預期值相同,才會更新數據
if (expectedState != null && oldState != expectedState) return false // CAS support
//如果2次發射的值相同,則丟棄,也就是做了防抖
if (oldState == newState) return true // Don't do anything if value is not changing, but CAS -> true
//CAS方式更新值
_state.value = newState
curSequence = sequence
//狀態更新序號變為偶數
if (curSequence and 1 == 0) { // even sequence means quiescent state flow (no ongoing update)
curSequence++ // +1,變成基數
sequence = curSequence
} else {
// 序號是奇數,說明該值已經更新過,立即返回
sequence = curSequence + 2 // +2,可以保持繼續奇數
return true // updated
}
curSlots = slots // read current reference to collectors under lock
}
這里大家暫時只需要關心2件事情,StateFlow通過CAS的方式保存和更新數據;如果前后2次發射的數據相同,會丟棄后一次,也就是說相同數據的發射,做了防抖過濾。
收集數據
override suspend fun collect(collector: FlowCollector<T>) {
val slot = allocateSlot() //分配槽位,和ShareFlow是一樣的
try {
if (collector is SubscribedFlowCollector) collector.onSubscription()
val collectorJob = currentCoroutineContext()[Job]
var oldState: Any? = null
// 也是和ShareFlow一樣的方式,開啟了一個死循環獲取數據
while (true) {
val newState = _state.value
// check協程是否取消
collectorJob?.ensureActive()
// 空安全檢查,如果前后2次發射數據不同,就會調用FlowCollector的emit方法,
//也就是會執行到collect{ }中的代碼塊
if (oldState == null || oldState != newState) {
collector.emit(NULL.unbox(newState))
oldState = newState
}
// 修改狀態,如果之前不是PENGDING狀態
if (!slot.takePending()) {
// 則掛起等待新數據更新
slot.awaitPending()
}
}
} finally {
// 釋放已分配的StateFlowSlot類型的對象
freeSlot(slot)
}
}
這個方法,我們暫時也不需要關注太多。只需要知道也是和ShareFlow一樣,開啟了死循環來獲取數據,數據的獲取就是前面通過atomic定義的_state
,所以state數據的收發都是通過CAS完成的。獲取到數據之后,會調用FlowCollector
的emit
方法,也就是會執行到collect{ }
中的代碼塊,這一點在之前文章介紹過。一個案例讓你秒懂kotlin flow原理
收集者(訂閱者)的管理
同ShareFlow,StateFlow也是用到了AbstractSharedFlow類,因此二者訂閱者管理的邏輯大致相同。區別是ShareFlow訂閱者數組中存儲的對象類為SharedFlowSlot
,而StateFlow中存儲的對象為StateFlowSlot
。
private val NONE = Symbol("NONE")
@SharedImmutable
private val PENDING = Symbol("PENDING")
// StateFlow 的每一個收集者都會分配一個卡槽
private class StateFlowSlot : AbstractSharedFlowSlot<StateFlowImpl<*>>() {
//用于存儲StateFlowSlot的狀態,一共有4個這狀態,初始值為null
private val _state = atomic<Any?>(null)
override fun allocateLocked(flow: StateFlowImpl<*>): Boolean {
// 如果_state的值不為null,表示槽位已被占用
if (_state.value != null) return false // not free
//_state的值為null,表示槽位可用,將_state的值設置為NONE,表示已被分配
_state.value = NONE // allocated
return true
}
override fun freeLocked(flow: StateFlowImpl<*>): Array<Continuation<Unit>?> {
//釋放槽位
//將_state的值設置為null,表示槽位現在可用。返回一個空的Continuation數組,表示沒有更多的操作需要執行
_state.value = null // free now
return EMPTY_RESUMES // nothing more to do
}
StateFlowSlot類型的對象共有四種狀態:
null
:表示已經空閑釋放,可以分配給消費者收集器NONE
: 表示已經分配給消費者接收器,但既沒有掛起,也沒有在處理當前的數據。PENDING
:表示表示上游已更新新值,待發送給收集器。CancellableContinuationImpl<Unit>
:表示收集器已掛起在等待上游數據