update an ObservableCollection with a BlockingCollection

若如初见. 提交于 2019-12-04 08:44:57

This is a perfect example of where the Reactive Extensions are a very useful and ingenious tool. There is a pretty steep learning curve to using them, but since you have a specific case here, I will insert the reactive code that will achieve your goal, assuming I understand your goal correctly.

Note that you will need to install the Reactive Extensions, and you will need two using statements (System.Reactive.Linq and System.Reactive.Subjects) and you will need to reference System.Reactive and System.Reactive.Windows.Threading dlls. See Reactive on MSDN.

class ElementHolder
{
    public ObservableCollection<Element> ElementsList { get; set; }
    private ExternalService _externalService = new ExternalService();
    private IDisposable _elementSubscription;
    private Subject<Element> _elementSubject = new Subject<Element>();

    public ElementHolder()
    {
        _externalService.ReceivedNewElement += _elementSubject.OnNext;
        _externalService.Subscribe();

        ElementList = new ObservableCollection<Element>();
        _elementSubscription = _externalService.ObserveOnDispatcher().Subscribe(NextElement);
    }

    private void NextElement(Element e)
    {
        Element item = ElementsList.FirstOrDefault(o => o.ID == element.ID);
        if (item == null) {
            _elementList.Add(element);
        }
        else {
            item.Update(element);
        }
    }
}

There's a small error in the answer. See the corrected line below:

_elementSubscription = _elementSubject.ObserveOnDispatcher().Subscribe(NextElement);

It took me a while to figure this out, but rmayer06's answer solved my problem. I can't comment on answers or I would have.

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