Search code examples
rxjsrxjs-observables

Rxjs create an observable that emits when a function is called


I'm likely missing something simple but can't quite puzzle this out from the docs. I'd simply like to have a function that when called will emit a value on an rxjs observable.

Psuedocode:

const myFunction = () => true //or whatever value
const myObservable = ... emit true whenever myFunction is called

...use myFunction somewhere where it being called is a useful event so 
observers of myObservable can process it

What's the standard pattern to emit a value when a function is called with rxjs?


Solution

  • You need a Subject for that https://www.learnrxjs.io/learn-rxjs/subjects

    Here is the reworked example from the documentation:

    import { Subject } from 'rxjs';
    
    const myObservable = new Subject<number>();
    
    const myFunction = () => {
      subject.next(1);
      subject.next(2);
    }
    
    myObservable.subscribe({
      next: (v) => console.log(`observerA: ${v}`)
    });
    myObservable.subscribe({
      next: (v) => console.log(`observerB: ${v}`)
    });
    
    // ...use myFunction somewhere where it being called is a useful event so 
    myFunction();
    

    Normally, you don't even need myFunction. Calling subject.next() would be enough.