在我當前的項目中,我正在處理firebase websocket訂閱。不同的組件可以訂閱不同的數據,例如,在每個ListItem
組件的訂單列表中,通過分派componentDidMount
中的SUBSCRIBE
動作和通過分派componentWillUnmount
中的UNSUBSCRIBE
動作取消訂閱,訂閱了該特定項目的websocket「事件」。使用redux-saga處理訂閱/取消訂閱大量事件
我的傳奇故事是這樣的:
const subscriptions = {}
export function * subscribeLoop() {
while (true) {
const { path } = yield take(SUBSCRIBE)
subscriptions[path] = yield fork(subscription, path)
}
}
export function * unsubscribeLoop() {
while (true) {
const { path } = yield take(UNSUBSCRIBE)
yield cancel(subscriptions[path])
}
}
export function * subscription (path) {
let ref
try {
const updateChannel = channel()
ref = api.child(path)
ref.on('value', snapshot => {
updateChannel.put(snapshot.val())
})
while (true) {
const data = yield take(updateChannel)
yield put(handleUpdate(path, data))
}
} finally {
if (yield cancelled()) {
ref.off()
ref = null
}
}
}
我想這是不處理這個正確的方式 - 它確實是500個項目的清單上相當緩慢。
如何優化性能?
- 我是否還需要分叉?
- 我應該引入某種延遲來給線程一些空間來處理其他事情嗎?
任何提示表示讚賞。