diff --git a/src/app/services/notifier.spec.ts b/src/app/services/notifier.spec.ts new file mode 100644 index 0000000..44a7cde --- /dev/null +++ b/src/app/services/notifier.spec.ts @@ -0,0 +1,27 @@ +import { fakeAsync, TestBed, tick } from '@angular/core/testing'; + +import { Notifier } from './notifier'; +import { Notification } from '../models/Notification'; + +describe('Notifier', () => { + let service: Notifier; + + beforeEach(() => { + TestBed.configureTestingModule({}); + service = TestBed.inject(Notifier); + }); + + it('should be created', () => { + expect(service).toBeTruthy(); + }); + + it('should set notification on notify and clean it after 800ms', fakeAsync(() => { + TestBed.tick(); + const NOTIFICATION_MOCK = new Notification('MOCK NOTIFICATION'); + service.notify(NOTIFICATION_MOCK); + expect(service.notification$()).toEqual(NOTIFICATION_MOCK); + TestBed.tick(); + tick(1000); + expect(service.notification$()).toEqual(null); + })); +}); diff --git a/src/app/services/notifier.ts b/src/app/services/notifier.ts new file mode 100644 index 0000000..f6e88a6 --- /dev/null +++ b/src/app/services/notifier.ts @@ -0,0 +1,25 @@ +import { effect, Injectable, signal } from '@angular/core'; +import { Notification } from '../models/Notification'; +@Injectable({ + providedIn: 'root', +}) +export class Notifier { + private readonly notification = signal(null); + readonly notification$ = this.notification.asReadonly(); + constructor() { + effect(() => { + if (this.notification$()) { + setTimeout(() => { + this.cleanup(); + }, 800); + } + }); + } + notify(notification: Notification) { + this.notification.set(notification); + } + + private cleanup() { + this.notification.set(null); + } +}