创建永无止境的订阅

时间:2018-08-27 22:03:57

标签: angular rxjs rxjs6

我要按照Angular cookbook中的说明从孩子与父母进行沟通。服务创建主题以通过其进行通信:

progressSubject = new Subject<ProgressMessage>

父级订阅主题并对消息做出反应

this.service.progressSubject.subscribe(msg => showProgress(msg))

客户可以使用progressSubject.next()发送消息,效果很好。 但是,如果我想将progressSubject订阅到另一个Observable,则如果源Observable完成,则所有订阅都将终止。父级将不再响应输入。

let first = new Subject();
first.subscribe(this.service.progressSubject);
first.next(3); // value is processed by subscribers to progressSubject
first.complete();

let second= new Subject();
second.subscribe(this.service.progressSubject);
second.next(3); // original subcription to progressSubject is ended, 
                // value is not processed anymore.

如何忽略某个主题的“完成”事件,以便多个源可以连接到该主题?

1 个答案:

答案 0 :(得分:1)

const first = new Subject();
const progressSubject = new Subject();
first.subscribe(progressSubject);

// is equal to

first.subscribe({
  next: val => progressSubject.next(val),
  error: err => progressSubject.error(err),
  complete: () => progressSubject.complete,
});

// if you don't need `complete` - just don't pass it )

first.subscribe({
  next: val => progressSubject.next(val),
  error: err => progressSubject.error(err),
});

我们也可以为此创建助手:

function skipComplete(subject){
  return {
    next: val => subject.next(val),
    error: err => subject.error(err),
  }
}

first.subscribe(skipComplete(progressSubject))

II

正如@IngoBürk所述,我们可以使用concat(NEVER)

first
  .pipe(concat(NEVER))
  .subscribe(progressSubject);