【问题标题】:Making a custom RXJS pipe that accepts an observable and waits until that observable meets a condition制作一个接受可观察对象并等待该可观察对象满足条件的自定义 RXJS 管道
【发布时间】:2020-01-24 00:00:19
【问题描述】:

我有以下代码

export function featureReady(feature: BaseFeatureService) {
  return pipe(
    zip(feature.loading$),
    filter(([inputObject, loading]) => !loading),
    map(([inputObject, loading]) => {
      return inputObject;
    })
  );
}

我希望像这样消费它。

observable$.pipe(
   featureReady(this.propertyFeatureService)
);

zip 现在已弃用以代替静态 zip,这意味着我的上述解决方案将停止工作是否有 RXJS 运算符我可以替换 zip 运算符或整个解决方案?

我也会对任何接受“可观察”等待条件的解决方案感到满意,因为我不介意传入feature.loading$

谢谢。

【问题讨论】:

    标签: angular typescript rxjs rxjs-pipeable-operators


    【解决方案1】:

    我环顾了其他运算符并找到了withLatestFrom,我可以使用它来获得与上面的zip 运算符相同的结果。

    现在看起来像这样:

    export function featureReady(feature: BaseFeatureService) {
      return pipe(
        withLatestFrom(feature.loading$),
        filter(([inputObject, loading]) => !loading),
        map(([inputObject, loading]) => {
          return inputObject;
        })
      );
    }
    

    如果有人有更好的解决方案,我会留下问题选项。

    【讨论】:

      【解决方案2】:

      最好使用 skipUntil Rxjs pipeable 操作符,它会跳过值直到内部 observable 满足某些条件。

      在下面的代码源中,Observable 将等待函数 fun 返回自定义管道,该管道将等待等待 observable 加载状态为 false

      const { interval, timer,of,concat } = rxjs;
      const {  skipUntil,delay,filter,ta } = rxjs.operators;
      
      
      // Write TypeScript code!
      const appDiv = document.getElementById('app');
      appDiv.innerHTML = `<h1>Wait until the loading status is false</h1>`;
      
      //custom pipe function which will  until loading
      const fun = (wait1) =>  skipUntil(wait1.pipe(filter(status => !status['loading'])));
      
      console.clear()
      const status = [{loading:true},{loading:false}]
      //emit every 1s
      const source = interval(1000);
      
      // inner obserbale which will emit the status after certain interval
      const wait1 = concat(of(status[0]).pipe(delay(1000)),of(status[1]).pipe(delay(3000))).pipe(delay(5000));
      //skip emitted values from source until inner observable emits false after the loading status turned to false
      const example = source.pipe(fun(wait1));
      
      const subscribe = example.subscribe(val => appDiv.innerHTML += 'interval ' + val + '<br/>');
      const subscribe1 = wait1.subscribe(val => appDiv.innerHTML += 'inner Observable status ' + val.loading + '<br/>');
      <script src="https://unpkg.com/rxjs/bundles/rxjs.umd.min.js"></script>
      
      <div id="app"></div>

      您可以找到stackBlitz solution

      【讨论】:

        猜你喜欢
        • 2022-08-19
        • 1970-01-01
        • 2018-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多