简体   繁体   中英

create observable<bool> from observablecollection

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?

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?

我注意到你有ReactiveUI标签 - 你是否使用ReactiveCollection,这将更容易:

coll.CollectionCountChanged.Select(x => x > 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM