Javascript 我可以将管道添加到现有的可观察对象吗

Javascript 我可以将管道添加到现有的可观察对象吗,javascript,rxjs,Javascript,Rxjs,我想要一个init函数来控制我的代码初始化过程,以提高可读性——这是一个路线图 myObservable$; init() { this.watchChanges() this.updateOptionsOnChange() this.patchValuesOnOptionUpdate(); } watchChanges () { myObservable$ = this.something.pipe( mergeMap(change => hitApi)

我想要一个init函数来控制我的代码初始化过程,以提高可读性——这是一个路线图

myObservable$;

init() {
  this.watchChanges()
  this.updateOptionsOnChange()
  this.patchValuesOnOptionUpdate();
}

watchChanges () {
  myObservable$ = this.something.pipe(
    mergeMap(change => hitApi)
  )
}

updateOptionsOnChange() {
  //here I want to "Add" a pipe to the existing pipes above
  myObservable$.pipe(
    tap(add values to an object/array)
  )
}

this.patchValuesOnChanges() {
  myObservable$.subscribe(
    set values based on above tap ^
  )
};
我可以这样做而不在UpdateOptions SonChange中进行另一个观察吗。这只是一个反模式吗?

您可以执行myObservable$=myObservable$。pipetap向对象/数组添加值。没有一种方法可以像您所描述的那样改变现有可观察对象的管道


如果有两个不同的观察对象,然后在patchValuesOnChanges中组合在一起,其中一个观察对象来源于UpdateOptions OnChange,可能会更具反应性。

在行为主体上使用开关映射来切换要使用的开关观察对象

const{BehaviorSubject,interval}=rxjs; const{switchMap,map}=rxjs.operators; 让useApi$=新行为SubjectFalse; 让switchButton=document.getElementById'switch'; switchButton.addEventListener'click',=>{ 如果使用API$.value{ switchButton.innerText='Local'; 使用API$.nextfalse; }否则{ switchButton.innerText='API'; 使用API$.nexttrue; } }; 让local$=interval1000.pipemap=>'local'; 让api$=interval1000.pipemap=>api; 让myObservable$=useApi$.pipe switchMapuseApi=>useApi?api$:本地$ ; myObservable$.subscribeval=>{console.logval;};
local您不应该更改属性上的可观察对象实例,您应该创建一个可观察对象,并将其切换到不同的路径。不要使用此技术,switchMap是您要寻找的答案。通过这种方式,您不断地创建和销毁可观察对象,我在第二段中提到了这种方法。第一段更接近地回答了这个问题。