| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="NotificationService.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Collections.Generic; |
| | | 9 | | using System.Linq; |
| | | 10 | | using System.Reactive.Linq; |
| | | 11 | | using System.Reactive.Subjects; |
| | | 12 | | using MyNet.UI.Notifications.Models; |
| | | 13 | | using MyNet.UI.Notifications.Processors; |
| | | 14 | | |
| | | 15 | | namespace MyNet.UI.Notifications; |
| | | 16 | | |
| | | 17 | | /// <summary> |
| | | 18 | | /// Implements a notification service that allows publishing notifications and processing them through a chain of proces |
| | | 19 | | /// </summary> |
| | | 20 | | public sealed class NotificationService : INotificationService, IDisposable |
| | | 21 | | { |
| | 30 | 22 | | private readonly Subject<INotification> _subject = new(); |
| | | 23 | | private readonly ISubject<INotification> _synchronizedSubject; |
| | | 24 | | private readonly IReadOnlyList<INotificationProcessor> _processors; |
| | | 25 | | private bool _isDisposed; |
| | | 26 | | |
| | | 27 | | /// <summary> |
| | | 28 | | /// Initializes a new instance of the <see cref="NotificationService"/> class. |
| | | 29 | | /// </summary> |
| | | 30 | | /// <param name="processors">An optional collection of notification processors to apply before publication.</param> |
| | | 31 | | public NotificationService(IEnumerable<INotificationProcessor>? processors = null) |
| | | 32 | | { |
| | 30 | 33 | | _synchronizedSubject = Subject.Synchronize(_subject); |
| | 30 | 34 | | _processors = processors?.ToList() ?? []; |
| | 30 | 35 | | } |
| | | 36 | | |
| | | 37 | | /// <inheritdoc/> |
| | 27 | 38 | | public IObservable<INotification> Notifications => _subject.AsObservable(); |
| | | 39 | | |
| | | 40 | | /// <inheritdoc/> |
| | | 41 | | public void Publish(INotification notification) |
| | | 42 | | { |
| | 33 | 43 | | ObjectDisposedException.ThrowIf(_isDisposed, this); |
| | | 44 | | |
| | 30 | 45 | | var current = notification; |
| | | 46 | | |
| | 60 | 47 | | foreach (var processor in _processors) |
| | | 48 | | { |
| | 0 | 49 | | current = processor.Process(current); |
| | 0 | 50 | | if (current is null) |
| | 0 | 51 | | return; |
| | | 52 | | } |
| | | 53 | | |
| | 30 | 54 | | _synchronizedSubject.OnNext(current); |
| | 30 | 55 | | } |
| | | 56 | | |
| | | 57 | | /// <inheritdoc/> |
| | | 58 | | public void Dispose() |
| | | 59 | | { |
| | 30 | 60 | | if (_isDisposed) |
| | 0 | 61 | | return; |
| | | 62 | | |
| | 30 | 63 | | _isDisposed = true; |
| | 30 | 64 | | _subject.OnCompleted(); |
| | 30 | 65 | | _subject.Dispose(); |
| | 30 | 66 | | } |
| | | 67 | | } |
| | | 68 | | |