Software IT-Consulting und Coaching

RxJs Observable acting as BehaviorSubject

The goal is to load data initially from a Promise (or somewhere else) into an Observable. Late subscribers shall get at least the latest published or even the initial value.

const updater = new Subject<string>();
const loader = async () => {
    return await Promise.resolve('loaded value');
};

const status$ = defer(() => loader()).pipe(merge(updater), shareReplay(1));

// Sub1: loaded value
status$.pipe(tap((val) => console.log(`Sub1: ${val}`))).subscribe();

// Sub1: Updated value
updater.next('Updated value');

// Sub2: Updated value
status$.pipe(tap((val) => console.log(`Sub2: ${val}`))).subscribe();