【问题标题】:Behaviorsubject and of() behave ina completely different wayBehaviorsubject 和 of() 的行为方式完全不同
【发布时间】:2020-08-20 17:12:47
【问题描述】:

我正在尝试创建一个可观察对象的处理链,其中第一步必须是一个主题(我需要调用 .next() )。使用 of() 有效,但返回一个 Observable,使用 BehaviorSubject 应该有类似的效果,但它不起作用:使用 of 创建的 observable 完美工作,订阅通过管道将数据带入并返回修改后的数据,而使用behaviorsubject 数据保留在主题中,订阅永远不会获取数据。

例子:

getProcessed(processed: string = null, identifier = 'default'): Observable<any> {
  const bs = new BehaviorSubject(this.start.data);
  this.localFilterSub.set(identifier, bs);
  this.localFilterObs.set(identifier, bs.asObservable());
  this.localFilterSet.set(identifier, {});
  this.process(processed, identifier);
  return this.localFilterObs.get(identifier);
}

process(name: string, identifier = 'default') {
  this.localFilterObs.set(identifier, this.doProcess(name, identifier));
}


private doProcess(name: string, identifier = 'default'): Observable<any>|Subject<any> {
  if (name) {
    const inst = new Op();

    const obss = [];
    obss.push(this.localFilterObs.get(identifier));
    obss.push(inst.getExternal());

    return forkJoin(obss).pipe(
      tap((data) => {
        console.log(name, data);
      }),
      map((data) => {
        return inst?.run(data);
        // this.done.push(name);
      }),
      tap((data) => {
        console.log(name, data);
      }),
    );
  } 
}

我真的不明白我做错了什么。

【问题讨论】:

  • “但它不起作用”是什么意思?什么不工作?你期望发生什么,实际发生了什么? BehaviorSubject 的行为方式与您使用 of 创建的 observable 的行为方式不同。
  • 为什么?使用 of 创建的 observable 将是具有给定数据集的 observable,behavioursubject 将是在订阅后立即发出数据的主题(这是一个 observable)。为什么会有区别?
  • 我同时编辑了这个问题。

标签: angular rxjs observable angular9 behaviorsubject


【解决方案1】:

在所有可观察对象完成之前,forkJoin 不会发出。 of 将立即完成,但在您调用完成之前,行为主题不会完成。使用 combineLatest,一旦所有的 observables 都发出,它就会发出。

const { BehaviorSubject, of, forkJoin } = rxjs;

const bs$ = new BehaviorSubject('bs');

o$ = of('of')

forkJoin([bs$, o$]).subscribe(res => { console.log(res); });

console.log('Nothing yet as bs$ not complete');

setTimeout(() => { bs$.complete(); }, 2000);
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.2/rxjs.umd.min.js"&gt;&lt;/script&gt;

但是 combineLatest 会立即发出

const { BehaviorSubject, of, combineLatest } = rxjs;

const bs$ = new BehaviorSubject('bs');

o$ = of('of')

combineLatest([bs$, o$]).subscribe(res => { console.log(res); });
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.2/rxjs.umd.min.js"&gt;&lt;/script&gt;

【讨论】:

    猜你喜欢
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    相关资源
    最近更新 更多