8

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?

2 Answers 2

11

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)
);
Sign up to request clarification or add additional context in comments.

1 Comment

Couldn't you just startWith({ target: this.nativeWindow }), when the startWith is before the map?
2

You can use startWith operator and pass an initial value to the observable

import { startWith } from 'rxjs/operators';

return fromEvent(this.nativeWindow, 'resize').pipe(
    startWith({ target: nativeWindow }),
    map(event => (event.target as Window).innerWidth)
);

1 Comment

Sorry. { target: nativeWindow } must be applied instead of nativeWindow.innerWidth

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.