简体   繁体   English

rxjs 条件 startWith

[英]rxjs conditional startWith

So what I am trying to do here is to use startWith conditionally based on another observable.所以我在这里尝试做的是基于另一个可观察对象有条件地使用 startWith 。

I tried mergeMap instead of map and wrapped the return values with 'of' but didn't work.我尝试了 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),

);

expecting the observable stream to start with false when mobile view and true otherwise.期望可观察流在移动视图时以 false 开头,否则以 true 开头。

you could define it like this:你可以这样定义它:

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)
  )));

You'll just end up canceling your previous click subscription and resubscribing everytime isMobileView$ emits, which shouldn't be a big deal.您最终只会取消之前的点击订阅并在每次 isMobileView$ 发出时重新订阅,这应该没什么大不了的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM