import { Injectable, OnDestroy } from '@angular/core';
import { map, debounceTime } from 'rxjs/operators';
import { Subscription, fromEvent } from 'rxjs';
interface Action {
id: string;
action: () => any;
}
@Injectable({
providedIn: 'root'
})
export class ResizeContentService implements OnDestroy {
private subscription: Subscription;
private listOfCallbacks: Action[] = [];
constructor() {
const resizeEvent = fromEvent(window, 'resize');
this.subscription = (resizeEvent.pipe(map(() => {
}), debounceTime(50)).subscribe(() => {
this.listOfCallbacks.forEach(f => f.action());
})
);
}
registerCallback(id: string, action: any) {
const actionToBePerformed: Action = { id: id, action: action};
this.listOfCallbacks.push(actionToBePerformed);
}
destroyCallback(id: string): void {
const filteredList = this.listOfCallbacks.filter(action => action.id !== id);
this.listOfCallbacks = filteredList;
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}