【问题标题】:Why observable is not observed为什么观察不到可观察的
【发布时间】:2021-07-08 20:38:08
【问题描述】:

我有两个级别的可观察对象,代码如下所示:

function level_1() {
    ...
    level_2(params).subscribe((value) => {
        if (value === something) {
            action_1();
        }
        else { // others
            action_2();
        }
    });
}

function level_2(params) : Observable<any> {
    ...

    another_observable.subscribe((v) => {
        if (a_condition) {
            return of(something); // this is reached, but the observable is not captured
        }
        else {
            return of (others);
        }
    });

    return of(others); // this is captured
}

现在的问题是,在三个“返回”中,level_1中只有第三个被捕获,而level_2中达到了第一个,而level_1中没有捕获到。 我虽然 observable 会继续听,但有什么我遗漏的吗?

【问题讨论】:

  • 什么是others。为什么你认为return of(something) 应该在level_2 中返回一些东西?那是完全不同的功能。他们不必互相做任何事情......
  • 我们可以认为这里有些东西是“真”,而另一些是“假”。我的问题是,为什么 level_1 函数中没有捕捉到 return of(true)。
  • 为什么你认为它应该。 another_observable.subscribe 确实与 level_2 返回的 observable 无关
  • 所以无论如何我都可以让 another_observable 发出可以被 level_1 捕获的东西: level_2(params).subscribe((value) {}

标签: javascript rxjs observable subscribe


【解决方案1】:

你可以从level_2返回一个observable,然后可以在level_1订阅:

function level_1() {
  level_2().subscribe(value => {
    if (value === 'something') {
      console.log('action_1')
    }
    else {
      console.log('action_2')
    }
  })
}

const another_observable = of(true) // This is just to make this example work

function level_2() {
  return another_observable.pipe(
    switchMap(value => {
      if (value) {
        return of('something')
      }
      else {
        return of('others')
      }
    })
  )
}

level_1()

...如果您只需要切换到一个值而不是另一个 observable,您可以使用 map 而不是 switchMap

function level_2() {
  return another_observable.pipe(
    map(value => {
      if (value) {
        return 'something'
      }
      else {
        return 'others'
      }
    })
  )
}

【讨论】:

    猜你喜欢
    • 2017-05-06
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    相关资源
    最近更新 更多