ReactiveUI和WhenAny中的选角
本文关键字:WhenAny ReactiveUI | 更新日期: 2023-09-27 18:27:06
我正在做的是:
Item.PropertyChanged += (sender, args) =>
{
if(sender is IInterface)
DoSomethingWith(((IInterface)sender).PropertyFromInterface);
}
我将如何在RxUI中实现这样的流?
我试过这个:
this.WhenAny(x => (x.Item as IInterface).PropertyFromInterface, x.GetValue())
.Subscribe(DoSomethingWith);
但这似乎是不可能做到的。
我必须建造这样的房产吗?->
private IInterface ItemAsInterface { get { return Item as IInterface; } }
我现在做了一个变通办法:
this.WhenAny(x => x.Item, x => x.GetValue()).OfType<IInterface>()
.Select(x => x.PropertyFromInterface).DistinctUntilChanged()
.Subscribe(DoSomethingWith);
但我真正想要的是在Item为IInterface时获得"PropertyFromInterface"的属性更改更新。
怎么样:
this.WhenAny(x => x.Item, x => x.Value as IInterface)
.Where(x => x != null)
.Subscribe(DoSomethingWith);
更新:好吧,我隐约明白你现在想做什么——我会怎么做:
public ViewModelBase()
{
// Once the object is set up, initialize it if it's an IInterface
RxApp.MainThreadScheduler.Schedule(() => {
var someInterface = this as IInterface;
if (someInterface == null) return;
DoSomethingWith(someInterface.PropertyFromInterface);
});
}
如果您真的想通过PropertyChanged:初始化它
this.Changed
.Select(x => x.Sender as IInterface)
.Where(x => x != null)
.Take(1) // Unsubs automatically once we've done a thing
.Subscribe(x => DoSomethingWith(x.PropertyFromInterface));
回顾我以前的问题,我正在寻找类似这样的解决方案:
this.WhenAny(x => x.Item, x => x.GetValue())
.OfType<IInterface>()
.Select(x => x.WhenAny(y => y.PropertyFromInterface, y => y.Value)
.Switch()
.Subscribe(DoSomethingWith);
我缺少的链接是.Switch方法。
此外,如果属性不是所需类型,我希望observable不做任何事情:
this.WhenAny(x => x.Item, x => x.Value as IInterface)
.Select(x => x == null ?
Observable.Empty :
x.WhenAny(y => y.PropertyFromInterface, y => y.Value)
.Switch()
.Subscribe(DoSomethingWith);
(例如,当我将this.Item
设置为IInterface
的实例时,我希望DoSomethingWith
侦听该实例的PropertyFromInterface
的更改,而当this.Item
设置为不同的值时,在this.Item
再次成为IInterface
的实例之前,可观察对象不应继续激发。)