[英]create observable<bool> from observablecollection
I have ObservableCollection<T> and I need to create observable<bool> which returns true if collection contains any elements 我有ObservableCollection <T>,我需要创建observable <bool>,如果collection包含任何元素,则返回true
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> 但我不知道如何将其转换为IObservable <bool>
How can I create observable<bool> from this? 如何从中创建可观察的<bool>?
You can use Select
to map the event into one of having elements: 您可以使用“
Select
将事件映射到具有以下元素之一:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.