Rxjs 创建一个在调用函数时发出的可观察对象

Rxjs create an observable that emits when a function is called

我可能遗漏了一些简单的东西,但无法从文档中完全弄清楚这一点。我只是想有一个函数,当被调用时会在 rxjs observable 上发出一个值。

伪代码:

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

当使用 rxjs 调用函数时发出值的标准模式是什么?

您需要使用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();

你需要 Subject https://www.learnrxjs.io/learn-rxjs/subjects

这里是文档中重新设计的示例:

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();

通常情况下,您甚至不需要 myFunction。调用 subject.next() 就足够了。