创建永不结束的订阅

Create subscription that never ends

我想按照 Angular cookbook 中的描述从 children 与 parent 进行通信。服务创建用于通信的主题:

progressSubject = new Subject<ProgressMessage>

parent 订阅主题并对消息做出反应:

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

客户端可以使用progressSubject.next()发送消息,效果很好。 但是,如果我想将 progressSubject 订阅到另一个 Observable,所有订阅都会在源 Observable 完成时终止。 parent 将不再对输入做出反应。

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.

如何忽略主题上的 "complete" 事件,以便多个源可以连接到该主题?

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

正如@IngoBürk 提到的,我们可以使用 concat(NEVER):

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