I try to get an observable of the window innerWidth.
I set a fromEvent observable watching on resize event
public get nativeWindow(): Window {
  return window;
}
public getWindowSize(): Observable<number> {
  return fromEvent(this.nativeWindow, 'resize').pipe(
    map(event => (event.target as Window).innerWidth)
  );
}
I want to be able to get the initial value of window.innerWidth because resize won't fire until actual window resize.
I could use BehaviorSubject but it forces me to subscribe to fromEvent to next on the subject.
We tried use a startWith(this.nativeWindow.innerWidth) operator before the map but the map then doesn't get the event argument as Event but get the startWith number instead.
Is there any rxjs operator which could allow me initialize first number before getting actual resize events?
So the problem is that you need map to process the initial value but at the same time you need it to work with Event objects that are only emitted by 'resize' event.
Well the easiest way is to just use startWith after map:
return fromEvent(this.nativeWindow, 'resize').pipe(
  map(event => (event.target as Window).innerWidth),
  startWith(this.nativeWindow.innerWidth)
);
or if this isn't possible (eg. the logic is more complicated) you can "mock" the object so map will process it like any other Event object.
return fromEvent(this.nativeWindow, 'resize').pipe(
  startWith({ target: { innerWidth: this.nativeWindow.innerWidth }}),
  map(event => (event.target as Window).innerWidth)
);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With