Alternative implementations of Redux source functi

2019-08-17 06:30发布

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?

标签: redux
0条回答
登录 后发表回答