For more tips like this, sign up to the weekly newsletter!
RxJS pairwise
with startWith
The pairwise
function is a great tool if you also need the previous value. But it does not emit for the first event.
const events = new rxjs.Subject();
events.pipe(
rxjs.operators.pairwise()
).subscribe(console.log.bind(console));
events.next(1);
events.next(2); // 1, 2
events.next(3); // 2, 3
Depending on your use case, it might be a good thing. But if you need an emit for every input event, combine it with startWith
.
const events = new rxjs.Subject();
events.pipe(
rxjs.operators.startWith(0),
rxjs.operators.pairwise()
).subscribe(console.log.bind(console));
events.next(1); // 0, 1
events.next(2); // 1, 2
events.next(3); // 2, 3
Use an initial value that makes sense for your use case. Usually, undefined
is a good candidate but always think about the consequences. It's also likely that special logic is needed for the first event.