问题
I am very confused on integrating Firebase with ngrx/store. Since Firebase has socket based "live" update, so the store data is already sync with Firebase data whenever I update Firebase. The problem is, I do not know how to listen to Firebase update and trigger a side effect with effect/store to do some more update on Firebase and the client store. Any suggestion on how should I approach this problem. For now, I have to use a long pull Observable.interval(5000) strategy to trigger a service function to query Firebase to find out if or not update is happened. The code is below:
@Effect() newMessages$ = Observable.interval(5000)
.withLatestFrom(this.store.select<UiState>("uiState"))
.map(([any,uiState]) => uiState)
.debug("We are querying Firebase to see if any update happened...")
.filter(uiState => Boolean(uiState.userId))
.switchMap(uiState => this.threadsService.loadNewMessagesForUser(uiState.userId)
.take(1)
.switchMap(data => this.threadsService.deleteMessagesQueuePerUser(uiState.userId).mapTo(data))
)
.debug("new messages received from server, and deleted temp record from Firebase")
.withLatestFrom(this.store.select<UiState>("uiState"))
.map(([unreadMessages, uiState]) => new NewMessagesReceivedAction({
unreadMessages,
currentThreadId: uiState.currentThreadId,
currentUserId: uiState.userId
}))
loadNewMessagesForUser and deleteMessagesQueuePerUser is firebase AngualrFire2 function. It basically use list to get (keep track) of new update on firebase, and delete the tracking data on firebase when we know what new update is happened since the last 5 second. I would love to remove that logic and just listen to firebase for update directly and trigger my side effect.
回答1:
In theory this should trigger continuouse updates and switch to a new-update stream when the uiState
changes.
@Effect() newMessages$ = this.store.select<UiState>("uiState")
.debug("We are querying Firebase to see if any update happened...")
.filter(uiState => Boolean(uiState.userId))
.switchMap(uiState => this.threadsService.loadNewMessagesForUser(uiState.userId)
.do(() => this.threadsService.deleteMessagesQueuePerUser(uiState.userId).subscribe())
.map(unreadMessages => new NewMessagesReceivedAction({
unreadMessages,
currentThreadId: uiState.currentThreadId,
currentUserId: uiState.userId
})
)
)
.debug("new messages received from server, and deleted temp record from Firebase");
来源:https://stackoverflow.com/questions/41857248/how-to-listen-to-firebase-update-and-trigger-effect-store-side-effect-to-update