Correct way to merge observable sequences for events fired from multiple instances

无人久伴 提交于 2019-12-06 12:23:39

Abusing Merge like that is not very efficient. The most straightforward way is via a Subject, which is an IObservable you control by hand.

public static class MyAwesomeFooFactory
{
    readonly static Subject<SomeEventArgs> someEvents = new Subject<SomeEventArgs>();

    public static IObservable<SomeEventArgs> NotificationsFromAllTheEvents { get { return someEvent; }}

    public static Foo MakeANewFoo()
    {
        var ret = new Foo();
        ret.SomeEvent.Subscribe(someEvents); // NB: We never unsubscribe, *evar*

        return ret;
    }
}

That is unlikely to work as you want, and has potentially stack-breaking performance issues. For every instance you add, you add another call to the stack between the first instance and the final observer. Get too many instances and you could blow the stack.

More important is the potentially wrong functionality. Does an observer expect to get notifications from all Foos created after it subscribes? In your current design they will not. If they should get notifications, you should change stream to a Subject<EventArgs> and have it subscribe to each Foo. The subject will serve as a merge point with the benefit that all of the subscribers to the subject will get the messages from instances created after the observer subscribed.

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