bitwarden-mobile/src/Core/Services/BroadcasterService.cs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

87 lines
2.2 KiB
C#
Raw Normal View History

2019-04-19 18:29:37 +02:00
using System;
using System.Collections.Generic;
2019-05-30 17:40:33 +02:00
using System.Threading.Tasks;
2019-04-19 18:29:37 +02:00
using Bit.Core.Abstractions;
using Bit.Core.Models.Domain;
namespace Bit.App.Services
{
public class BroadcasterService : IBroadcasterService
{
private readonly ILogger _logger;
2019-04-19 18:29:37 +02:00
private readonly Dictionary<string, Action<Message>> _subscribers = new Dictionary<string, Action<Message>>();
2019-06-05 03:28:50 +02:00
private object _myLock = new object();
2019-04-19 18:29:37 +02:00
public BroadcasterService(ILogger logger)
{
_logger = logger;
}
public void Send(Message message)
2019-04-19 18:29:37 +02:00
{
lock (_myLock)
2019-04-19 18:29:37 +02:00
{
foreach (var sub in _subscribers)
2019-04-19 18:29:37 +02:00
{
Task.Run(() =>
2019-06-05 03:28:50 +02:00
{
try
{
sub.Value(message);
}
catch (Exception ex)
{
_logger.Exception(ex);
}
});
2019-06-05 03:28:50 +02:00
}
}
}
public void Send(Message message, string id)
{
if (string.IsNullOrWhiteSpace(id))
{
return;
}
lock (_myLock)
{
if (_subscribers.TryGetValue(id, out var action))
2019-06-05 03:28:50 +02:00
{
Task.Run(() =>
{
try
{
action(message);
}
catch (Exception ex)
{
_logger.Exception(ex);
}
});
2019-04-19 18:29:37 +02:00
}
}
}
public void Subscribe(string id, Action<Message> messageCallback)
{
lock (_myLock)
2019-04-19 18:29:37 +02:00
{
_subscribers[id] = messageCallback;
2019-04-19 18:29:37 +02:00
}
}
public void Unsubscribe(string id)
{
lock (_myLock)
2019-04-19 18:29:37 +02:00
{
if (_subscribers.ContainsKey(id))
2019-06-05 03:28:50 +02:00
{
_subscribers.Remove(id);
}
2019-04-19 18:29:37 +02:00
}
}
}
}