improvement: Make DataStreamSubscription an IHostedService

To properly manage its life cycle
This commit is contained in:
John Colvin committed 2024-07-11 10:37:28 -04:00
1 parent 451f721030
commit fbfc960df6
1 file changed
+17 -4
@@ -12,22 +12,23 @@ using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
class DataStreamSubscription : IDisposable {
class DataStreamSubscription : IDisposable, IHostedService {
public readonly ViewStream ViewStream;
public DataPacket? LastFired;
public readonly string Id;
readonly ILogger logger;
readonly WebSocket webSocket;
readonly DataPacketJsonSerializer dataPacketSerializer = new();
public DataStreamSubscription(string id, ViewStream viewStream, WebSocket webSocket, ILogger logger) {
public DataStreamSubscription(string id, JsonRpcId requestId, ViewStream viewStream, WebSocket webSocket, ILogger logger) {
ViewStream = viewStream;
RequestId = requestId;
Id = id;
this.webSocket = webSocket;
this.logger = logger;
}
public string Id { get; }
public JsonRpcId RequestId { get; }
public SubscriptionStatus Status { get; private set; }
public void Start() {
@@ -40,6 +41,12 @@ class DataStreamSubscription : IDisposable {
ViewStream.onChange += onChange;
}
public Task StartAsync(CancellationToken cancellationToken) {
cancellationToken.ThrowIfCancellationRequested();
Start();
return Task.CompletedTask;
}
public Task Clear() {
if (LastFired is null) {
return Task.CompletedTask;
@@ -58,6 +65,12 @@ class DataStreamSubscription : IDisposable {
ViewStream.onChange -= onChange;
}
public Task StopAsync(CancellationToken cancellationToken) {
cancellationToken.ThrowIfCancellationRequested();
Stop();
return Task.CompletedTask;
}
public void Dispose() =>
Stop();