3
votes

So what I am trying to do here is to use startWith conditionally based on another observable.

I tried mergeMap instead of map and wrapped the return values with 'of' but didn't work.

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.

1
is this.isMobileView$ a behavior subject?bryan60
no it's Observable<boolean>Wildhammer
I meant it's source, but it doesn't matter, answered below.bryan60

1 Answers

2
votes

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.