【问题标题】:rxjs conditional startWithrxjs 条件 startWith
【发布时间】:2019-09-21 11:22:37
【问题描述】:

所以我在这里尝试做的是基于另一个可观察的有条件地使用 startWith。

我尝试了 mergeMap 而不是 map,并用 'of' 包装了返回值,但没有奏效。

fromEvent(element.nativeElement,'click').pipe(
    withLatestFrom(this.isMobileView$),
    map(([event, isMobileView]) => {
        if (isMobileView) {
            // do some stuff
            return false;
        } else {
            // do some other stuff
            // return a boolean variable
            return this._drawer.opened;
        }// TODO: else if nativescript
    }),
    //here I want to use 'isMobileView' inside my startWith
    //   something like startWith(!isMobileView)
    startWith(true),

);

期望可观察流在移动视图时以 false 开头,否则以 true 开头。

【问题讨论】:

  • this.isMobileView$ 是行为主体吗?
  • 不,它是可观察的
  • 我的意思是它的来源,但没关系,在下面回答。

标签: angular typescript rxjs


【解决方案1】:

你可以这样定义它:

this.isMobileView$.pipe(switchMap(isMobileView => 
  fromEvent(element.nativeElement,'click').pipe(
    map((event) => {
        if (isMobileView) {
            // do some stuff
            return false;
        } else {
            // do some other stuff
            // return a boolean variable
            return this._drawer.opened;
        }
    }),
    startWith(!isMobileView)
  )));

您最终会取消之前的点击订阅并在每次 isMobileView$ 发出时重新订阅,这应该没什么大不了的。

【讨论】:

    猜你喜欢
    • 2021-05-25
    • 1970-01-01
    • 2019-06-13
    • 2020-09-04
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    相关资源
    最近更新 更多