Angular Firestore中监听特定键值变化问题排查——getUserEventSummaryE函数非目标字段变更时误触发
Hey there! I see the issue here—your current listener is comparing the entire document object for changes, which is why any field update (even unrelated ones like userbalance or dob) is triggering a new emission. Let's adjust this to only react when the playing_summary field changes.
The Problem with Your Current Code
Your distinctUntilChanged operator uses _.isEqual(prev, curr) to compare full document objects. This means any field modification will make the comparison return false, causing the stream to emit the updated document—even when the change has nothing to do with playing_summary.
The Solution
Modify the distinctUntilChanged comparison function to only check if the playing_summary field has changed, instead of validating the entire document:
getUserEventSummaryE(userId) { return docData(doc(this.firestore, `/user/${userId}/event_summary/current/`), {idField: 'playing_summary'}) .pipe( // Only compare the playing_summary field between previous and current values distinctUntilChanged((prev, curr) => _.isEqual(prev.playing_summary, curr.playing_summary)) ); }
How This Works
- We still fetch the complete document data with
docData, so you’ll get the full document wheneverplaying_summarychanges. - The
distinctUntilChangedoperator now only checks if theplaying_summaryfield is identical (deeply, thanks to Lodash’s_.isEqual) between the previous and current document state. - Updates to other fields like
userbalanceordobwill result in_.isEqual(prev.playing_summary, curr.playing_summary)returningtrue, so those irrelevant changes are filtered out and won’t trigger your subscription.
Quick Notes
- If
playing_summaryis a simple value (string, number, boolean), you could replace_.isEqualwith a strict equality check (prev.playing_summary === curr.playing_summary). But_.isEqualis safer long-term—it handles deep comparisons automatically ifplaying_summaryever becomes a nested object or array.
内容的提问来源于stack exchange,提问作者cakePHP

