create observable<bool> from observablecollection

.net, c#, reactive-programming, reactiveui, system.reactive

Solution

You can use `Select` to map the event into one of having elements:

        ObservableCollection<int> coll = new ObservableCollection<int>();

        var hasElements = 
        Observable.FromEventPattern<NotifyCollectionChangedEventHandler,NotifyCollectionChangedEventArgs>(
            a => coll.CollectionChanged += a,
            a => coll.CollectionChanged -= a)
        .Select(_ => coll.Count > 0);

Example:

        hasElements.Subscribe(Console.WriteLine);

        coll.Add(1);
        coll.Add(2);
        coll.Remove(1);
        coll.Remove(2);

Output:

True
True
True
False

Is this what you were looking for?

Problem

I have ObservableCollection<T> and I need to create observable<bool> which returns true if collection contains any elements I try to do this ``` var collectionHasElementsObservable = Observable.FromEventPattern<NotifyCollectionChangedEventHandler,NotifyCollectionChangedEventArgs>( ev => ((ObservableCollection<MyType>)_items).CollectionChanged += ev, ev => ((ObservableCollection<MyType>)_items).CollectionChanged -= ev); ``` But I don't know how to convert this into IObservable<bool> How can I create observable<bool> from this?

Original source