IServiceObservable
IServiceObservable exposes IObservable<ServiceEvent>.
/// <summary>Service that can be observed for internal state changes.</summary>
public interface IServiceObservable : IServiceBase, IObservable<ServiceEvent> { }
/// <summary>Base class for service events</summary>
public record ServiceEvent(IServiceBase sender);
/// <summary>Service closed event</summary>
public record ServiceClosedEvent(IServiceBase sender) : ServiceEvent(sender);
.Subscribe(observer) attaches observer to service.
// Create service
IServiceObservable service = (IServiceObservable)Services.Create(ServiceHandlers.Instance);
// Add observer
service.Subscribe(new ServiceObserver());
// Close service
((IDisposable)service).Dispose();
public class ServiceObserver : IObserver<ServiceEvent>
{
public void OnCompleted() => WriteLine("Completed");
public void OnError(Exception error) => WriteLine($"Error: {error}");
public void OnNext(ServiceEvent value) => WriteLine(value);
}
Full Example
Full example
using System;
using Avalanche.Service;
using static System.Console;
public class service_observable
{
public static void Run()
{
{
// <01>
// Create service
IServiceObservable service = (IServiceObservable)Services.Create(ServiceHandlers.Instance);
// Add observer
service.Subscribe(new ServiceObserver());
// Close service
((IDisposable)service).Dispose();
// </01>
}
}
// <99>
public class ServiceObserver : IObserver<ServiceEvent>
{
public void OnCompleted() => WriteLine("Completed");
public void OnError(Exception error) => WriteLine($"Error: {error}");
public void OnNext(ServiceEvent value) => WriteLine(value);
}
// </99>
}