问题
I am trying to write an observable that will update database to 'away'status depending on mouseover document. And if mouse active, update back to 'online'.
Here is what I have so far:
private updateOnIdle(userId) {
this.timer$ = fromEvent(document, 'mousemove')
.pipe(
first(),
throttleTime(2000),
switchMap(() => firebase.database()
.ref(`/status/${userId}`).set({status: 'online', last_changes: firebase.database.ServerValue.TIMESTAMP}),
),
map(() =>
timer(5000)
.map(() => {
firebase.database().ref('/status/' + userId).set({
status: 'away',
last_changed: firebase.database.ServerValue.TIMESTAMP
});
})
)
);
}
But this doesn't work for me. What would be the way to do it?
回答1:
You almost have it, really just need to subscribe()
in a couple of places.
To make things clearer in the sample below I have abstracted away the Firebase code and for demo purposes replaced it with a console.log()
.
I also changed the timer(5000).map()
to pipeable format, since you already have .pipe()
above. It should work either way if you have the correct imports, but better to keep it all consistent.
Finally, I dropped the first()
since presume the code should keep monitoring the mouse over time.
With this working now, you can see in the console what Firebase will see as the mouse is moved in various patterns.
The next enhancement may be to suppress 'online' updates when already online, but that depends on your requirement.
console.clear()
fromEvent = rxjs.fromEvent
first = rxjs.operators.first
throttleTime = rxjs.operators.throttleTime
switchMap = rxjs.operators.switchMap
map = rxjs.operators.map
timer = rxjs.timer
of = rxjs.of
userId = 1
/*
setStatus = (newStatus, userId) => {
return firebase.database()
.ref(`/status/${userId}`)
.set({
status: newStatus,
last_changed: firebase.database.ServerValue.TIMESTAMP
})
}
*/
setStatus = (newStatus, userId) => {
console.log(newStatus, userId)
return of(1)
}
timer$ = fromEvent(document, 'mousemove').pipe(
//first(),
throttleTime(2000),
switchMap(() => setStatus('online', userId)),
map(() =>
timer(5000).pipe(
map(() => setStatus('away', userId))
).subscribe()
)
);
timer$.subscribe();
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.2.0/rxjs.umd.js"></script>
来源:https://stackoverflow.com/questions/50744593/how-to-write-an-observable-that-unsubscribes-itself-rxjs6-angular6