1

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?

imagio
  • 1,390
  • 2
  • 16
  • 27

2 Answers2

4

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.

sneas
  • 924
  • 6
  • 23
1

You need to use Subject.


const subject = new Subject(); // a subject to notify
const myObservable = subject.asObservable();

const myFunction = () => {
  subject.next(true);
};

myObservable.subscribe(console.log);

myFunction();
myFunction();
myFunction();

satanTime
  • 12,631
  • 1
  • 25
  • 73