How to avoid the use of Subjects in RX

馋奶兔 提交于 2019-12-04 01:12:55

It's not so much that the use of Subject<T> is bad - there has to be some way of "entering the monad" - that's the academic way of saying "get an IObservable<T>". You need to start somewhere.

The problem with Subject<T> arises more when it's used from a subscription instead of chaining existing observables together. Subjects should just exist at the edges of your Rx machinery.

If none of the provided entry points (e.g. FromEvent, FromEventPattern, FromAsync, Return, ToObservable() and so on) work for you then using Subject<T> is perfectly valid. And there's no need to add extra complexity just to facilitate using one of the above - most of them use subjects or subject-like constructs under the covers anyway.

In your case, sounds like Subject<T> is just fine. You might what to look at exposing it via AsObservable() in order to hide the implementation details.

A simple way to enter the observable is via an Action

private Action<ObservableArgs> _action;

Create the observable

public IObservable<ObservableArgs> GetObservable()
{
    return Observable.FromEvent<ObservableArgs>>(
                ev => _action += ev, 
                ev => _action -= ev);
}

Then add to the observable using

public void OnNext(ObservableArgs args)
{
    _action?.Invoke(args);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!