为什么不观察可观察

bkkx9g8r  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(339)

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

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
}

现在的问题是,在三个“返回”中,只有第三个在级别_1中被捕获,但第一个在级别_2中被到达,但在级别_1中没有被捕获。我认为observable将继续倾听,我缺少什么吗?

mnowg1ta

mnowg1ta1#

您可以从 level_2 ,然后可以在中订阅 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()

…或者你可以使用 map 而不是 switchMap 如果您只需要切换到一个值而不是另一个可观察值:

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

相关问题