dimanche 8 novembre 2020

How to substitute an event-based class for an observable-based class in C# and System.Reactive?

I have a class which has some events. At present, I decide to shift towards "Observables" since the benefits they propose. To reach this goal, I introduced an Observable property to be replaced with one of the events. Next, I made the event "private" to restrict its accessibility from out of the class. The event is invoked inside the class with a function when it is needed. However, I think It may be a better way to do this job. What is the proper practice? By the way, I am a novice in "System.Reactive," so if I have a misunderstanding with the concept, please clarify the matter. My code is below:

public class MyClass
{
    public MyClass()
    {
        InformationSenderObservable=Observable.FromEventPattern<SolutionEventArg>(ev =>InformationSender += ev, ev => InformationSender -= ev);
    }
    private event EventHandler<SolutionEventArg> InformationSender;
    public IObservable<EventPattern<SolutionEventArg>> InformationSenderObservable { get; }

    internal void DoSomething()
    {
        // long calculation
        SendInformation();
    }

    private void SendInformation()
    {
        InformationSender?.Invoke(this,new SolutionEventArg()
            {
                InfoProxyData = GetDetailsForBestCompressedData(),
                ParallelProcess = parallelProcessing
            });
    }
}

Aucun commentaire:

Enregistrer un commentaire