Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add initial value in fromEvent resize observable

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?

like image 392
BlackHoleGalaxy Avatar asked Aug 31 '18 11:08

BlackHoleGalaxy


1 Answers

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)
);
like image 115
martin Avatar answered Sep 20 '22 13:09

martin