在WhenAny中进行ReactiveUI和强制转换

时间:2013-08-11 00:24:47

标签: c# reactiveui

我正在做的是:

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);

但我真正想要的是获取“PropertyFromInterface”的属性更新,而Item是IInterface。

2 个答案:

答案 0 :(得分:1)

怎么样:

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));

答案 1 :(得分:0)

回答我的旧问题,我正在寻找类似这样的解决方案:

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的实例之前,observable不应继续触发。)