Invoking observables with Subject next() not working

ⅰ亾dé卋堺 提交于 2019-12-14 03:29:26

问题


Why does this function only work once? I click a button to call the next() on the Subject queue which works but if I click the other button it doesn't work.

  getData(text): Observable<string> {
    const timer$ = timer(2000);

    const observable = new Observable<string>(observer => {

      timer$.pipe(
        map(() => {
          observer.next('http response ' + text);
        })
      ).subscribe();

    });
    return observable;
  }

I setup a Subject and use next() which should make the observable emit data.

  queue = new Subject();
  streamA$: Observable<string>;
  streamB$: Observable<string>;
  images$: Observable<string>;

  constructor(private timerService: TimerService) {

  }

  ngOnInit() {
    this.streamA$ = this.timerService.getData('a');
    this.streamB$ = this.timerService.getData('b');
    this.images$ = this.queue.pipe(concatMap((data: string) => data));
  }

  clickA() {
    this.queue.next(this.streamA$);
  }

  clickB() {
    this.queue.next(this.streamB$);
  }

Template:

<button (click)="clickA()">Click A</button>
<button (click)="clickB()">Click B</button>
<div>{{images$ | async}}</div>

https://stackblitz.com/edit/angular-subject-queue


回答1:


You're using concatMap(). This emits all the events emitted from the first observable emitted by the subject, then all the events emitted by the second observable emitted by the subject.

But the first observable never completes, so there's no way for the second observable to ever emit anything.

If you want the observable returned by the service to emit once after 2 seconds then complete, all you need is

return timer(2000).pipe(
  map(() => 'http response ' + text)
);


来源:https://stackoverflow.com/questions/57521478/invoking-observables-with-subject-next-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!