Alternative implementations of Redux source function ensureCanMutateNextListeners?

喜欢而已 提交于 2019-12-25 16:00:23

问题


I am reading redux source, and the ensureCanMutateNextListeners function caught my eyes. The comments in the source explained very well, I can understand.

However, I just felt it is a bit complex, (i.e., two listeners collections and call ensureCanMutateNextListeners before manipulate the collections), I am thinking if it is possible to simplify and still solve the original problem. The below are the two options I can think of:

Original problem to solve:

Keep a stable listeners when dispatching, avoid uncertain issues due to listeners changes when dispatching

Option #1: immutable collections

When changing, set a new listeners array instead of modify the existing one. At any moment when dispatch happens, it get a listener array which is a snapshot and will never change.

let currentListeners = [] // just one listeners collections

// in dispatch
const listeners = currentListeners
for (let i = 0; i < listeners.length; i++) {
    listener()
}

// when subscribe a listener, just push
currentListeners = [...currentListeners, listener]

// when unsubscribe a listener, just get rid of
currentListeners.splice(index, 1) 

Option #2: slice in dispatch At any moment when dispatch happens, it get a clone of the listeners first, it is just like a snapshot.

let currentListeners = [] // just one listeners collections

// in dispatch
const listeners = currentListeners.slice()
for (let i = 0; i < listeners.length; i++) {
    const listener = listeners[i]
    listener()
}

// when subscribe a listener, just push
currentListeners.push(listener)

// when unsubscribe a listener, just get rid of
currentListeners = currentListeners.filter(x=>x === listener) 

IMO, either one of the above solutions is much simpler than the original implementation in redux source. I am wondering if I miss anything, any thoughts are welcome.

Reference question: React Redux source function ensureCanMutateNextListeners?

来源:https://stackoverflow.com/questions/45746097/alternative-implementations-of-redux-source-function-ensurecanmutatenextlistener

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!