gpt4 book ai didi

reactjs - 如何将 Firestore 实时更新(onSnapshot)与 redux-observable/rxjs 结合使用?

转载 作者:行者123 更新时间:2023-12-03 13:47:28 24 4
gpt4 key购买 nike

我可以使用普通的 Firestore 查询设置 redux-observable

export const getStatementsEpic = (action$, store) => {
return action$.ofType(GET_STATEMENTS)
.filter(() => {
const state = store.getState()
return state.auth.user
})
.mergeMap(() => {
console.log('action', store.getState().auth.user.uid)
const db = firebase.firestore()
db.settings({ timestampsInSnapshots: true })
const query = db.collection('users')
.doc(store.getState().auth.user.uid)
.collection('statements')
.orderBy('uploadedOn', 'desc')
.limit(50)
return query.get().then(snapshot => {
console.log('Should have gotten snapshot')
return getStatementsSnapshot(snapshot)
})
})
}

但我想将其转换为实时,我尝试更改

return query.get().then(snapshot => {

return query.onSnapshot(snapshot => {

但是它不起作用......我想这不是一个 promise ?我该如何解决这个问题?

最佳答案

你是对的,onSnapshot 方法不会返回 promise 。相反,它返回一个可用于取消订阅更改通知的函数。在调用取消订阅函数之前,每次文档更改时都会调用传递给 onSnapshot 方法的回调。 (documentation 表示回调也将立即使用当前文档内容调用。)

onSnapshot这样多次使用回调函数的函数可以使用fromEventPattern函数“转换”为可观察对象。 fromEventPattern 采用两个函数作为参数。您传递的第一个函数需要调用 onSnapshot,并将 RxJS 定义的处理程序作为回调传递给它。您传递的第二个函数需要调用 onSnapshot 返回的取消订阅函数。当您订阅可观察对象时(即在您的史诗中使用它),RxJS 将调用第一个函数。当您取消订阅可观察对象时,RxJS 将调用第二个函数。

以下是更新为使用 fromEventPattern 和新 RxJS 管道的代码示例:

export const getStatementsEpic = (action$, state$) => action$.pipe(
ofType(GET_STATEMENTS),
withLatestFrom(state$),
filter(([action, state]) => state.auth.user),
mergeMap(([action, state]) => {
const db = firebase.firestore()
db.settings({ timestampsInSnapshots: true })
return fromEventPattern(
handler => db.collection('users')
.doc(state.auth.user.uid)
.collection('statements')
.orderBy('uploadedOn', 'desc')
.limit(50)
.onSnapshot(handler),
(handler, unsubscribe) => unsubscribe(),
).pipe(
map(getStatementsSnapshot),
takeUntil(action$.pipe(
ofType(STOP_GET_STATEMENTS),
)),
)
}),
)

请注意,我已将 takeUntil 引入到快照流中。没有它(或类似的东西),快照流将永远不会结束。另一个可能的更改是使用 switchMap 而不是 mergeMap。如何取消订阅仅取决于您的用例。

关于reactjs - 如何将 Firestore 实时更新(onSnapshot)与 redux-observable/rxjs 结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50655236/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com