【问题标题】:Calling subscribe inside subscribe在 subscribe 中调用 subscribe
【发布时间】:2018-09-27 16:46:56
【问题描述】:

有两个相互依赖的变量(颜色和图片)。 取决于以下含义:当变量颜色的值为“蓝色”时,我想过滤所有具有蓝色等颜色的图片。 可变图片是一个带有服务/后端调用的主题:

this.colorSubject.subscribe((color) => {
      subject.switchMap((searchTerm: string) => serviceCall(searchTerm, color) ).subsribe(...)
});

为此,我需要监听颜色变量的变化,然后调用上面的代码行。 但这会导致服务的多次调用。

任何想法如何处理这个问题?

【问题讨论】:

  • 你能发布完整的复制品吗?还有什么确切地的问题?你说你在复制代码,但我在这里看不到任何重复的东西。我们可以看看你是如何制作它的,然后我们可以帮助推广它吗?
  • 颜色也是流吗?如果不是 - 它应该是。然后你可以简单地将地图从可观察的颜色切换到你描述的可观察对象
  • 我粘贴了代码。

标签: angular observable subscribe subject switchmap


【解决方案1】:

如果我对您的理解正确,您需要第三个流来表示color 和pictures 的合并结果。我们称之为filteredPictures$。该流应该使用color 和pictures 使用combineLatest。现在,如果任一流发生变化,filteredPictures$ 将通知所有订阅者新值。

const {
  Subject,
  from,
  combineLatest
} = rxjs;
const {
  withLatestFrom,
  switchMap
} = rxjs.operators;

const color = new Subject();
const pictures = new Subject();

function service(searchTerm = "house", colorTerm = "green") {
  return Promise.resolve([`${searchTerm}.jpg`, `${colorTerm}.png`]);
}

const color$ = color.asObservable();
const pictures$ = pictures.asObservable();
const filteredPictures$ = combineLatest(
  pictures$,
  color$
).pipe(switchMap(([searchTerm, colorTerm]) => from(service(searchTerm, colorTerm))));

filteredPictures$.subscribe(console.log);

pictures.next("water");
setTimeout(() => {
  color.next("yellow");
  setTimeout(() => {
    pictures.next("helicoptor");
    setTimeout(() => {
      color.next("red");
    }, 1000);
  }, 1000);
}, 1000);
<script src="https://unpkg.com/rxjs/bundles/rxjs.umd.min.js"></script>

【讨论】:

  • 是的,这就是我正在寻找的。但是还有一点:一开始没有服务调用?
猜你喜欢
  • 1970-01-01
  • 2020-11-29
  • 1970-01-01
  • 1970-01-01
  • 2020-11-16
  • 1970-01-01
  • 2021-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多