Angular Material Flex MediaObserver Subscribed Twice

Viewed 269

I am using Material Flex Layout for detection of screen size.But I get subscribed result twice.The Same Code at another Angular project results fine.

constructor(
    public mediaObserver: MediaObserver) {
     mediaObserver.media$.subscribe((change: MediaChange) => {
      if ( change.mqAlias == 'xs') {

        console.log('xsA');
      }else  if ( change.mqAlias == 'sm') {
        console.log('xsB');
      }else{
        console.log('xsC');
      }

    });
}

This is my code .

1 Answers

It is hard to say why you get two emissions with the code you provided. But as a workaround you can use rxjs distinctUntilKeyChanged operator;

constructor(public mediaObserver: MediaObserver) {
  mediaObserver.media$.pipe(distinctUntilKeyChanged('mqAlias'))
    .subscribe((change: MediaChange) => {
      if (change.mqAlias == 'xs') {
        console.log('xsA');
      } else if (change.mqAlias == 'sm') {
        console.log('xsB');
      } else {
        console.log('xsC');
      }
    });
}

Also, I found following issues which might be related;

https://github.com/angular/flex-layout/issues/504

https://github.com/angular/flex-layout/issues/1059

Related