You can use two subscribers, one for the default case to be applied to all events and the other for the special case of the first event:
import { of } from 'rxjs';
import { first } from 'rxjs/operators';
//emit 4 values
const source = of(1, 2, 3, 4);
/*
Subscriber One - only first value: 1
Subscriber Two - all values: 1
Subscriber Two - all values: 2
Subscriber Two - all values: 3
Subscriber Two - all values: 4
*/
const subscriberOne = source
.pipe(first())
.subscribe((val) => console.log(`Subscriber One - only first value: ${val}`));
const subscriberTwo = source.subscribe((val) =>
console.log(`Subscriber Two - all values: ${val}`)
);
see it live on stackblitz
And to answer your question, where there is a special handler for the first event and then a common handler for the rest of the event, excluding the first one:
import { of, skip } from 'rxjs';
import { first, publish } from 'rxjs/operators';
// emit 4 values
const source = of(1, 2, 3, 4);
// hold until `others` until `connect()` is called, skip `source` first event
const others = publish()(source.pipe(skip(1)));
// marker to make sure first event handler ran before the others
let onceRan = false;
// general case, has to be declared before so `others.subscribe()`
// runs before `others.connect()` is called
const subscriberTwo = others.subscribe((val) =>
console.log(`Subscriber Two - all values: ${val}, onceRan: ${onceRan}`)
);
// first event handler, `first()` => stops after the first event
const subscriberOne = source.pipe(first()).subscribe((val) => {
console.log(`Subscriber One - only first value: ${val}, onceRan: ${onceRan}`);
// toggle the merker
onceRan = true;
// release `others`
others.connect();
});
/*
Output:
Subscriber One - only first value: 1, onceRan: false
Subscriber Two - all values: 2, onceRan: true
Subscriber Two - all values: 3, onceRan: true
Subscriber Two - all values: 4, onceRan: true
*/
see it live on stackblitz
takeFirst
operator. If you are usingswitchMap
, its projection function is passed anindex
parameter. I'd suggest you use that to identify the first emitted value. – Forenamed