在ReactiveExtensions中如何从可枚举的元素中选择元素?

时间:2017-11-17 06:41:16

标签: c# reactive-programming

像往常一样很难解释我的Rx问题,所以让代码进行讨论:

public class Feature
{
    public ReactiveProperty<bool> IsRunning = new ReactiveProperty<bool>(false);
}

public class MyHelpers
{
    public static ReadOnlyReactiveProperty<Feature> GetRunningFeature(IEnumerable<Feature> features)
    {
        // How do I return the latest running feature?
        // AND support disposing so no memory leaks
    }
}

public class TestMyHelpers
{
    public void Tests()
    {
        var features = new List<Feature>() {new Feature(), new Feature(), new Feature()};
        var running = MyHelpers.GetRunningFeature(features);

        features[1].IsRunning.Value = true;
        Assert.AreEqual(features[1], running.Value);

        features[2].IsRunning.Value = true;
        Assert.AreEqual(features[2], running.Value);

        features[2].IsRunning.Value = false;
        Assert.AreEqual(features[1], running.Value);

        features[1].IsRunning.Value = false;
        Assert.AreEqual(null, running.Value);
    }
}

基本上我想要一个解决方案,在给出IEnumerable功能的初始输入的情况下返回最新的运行功能,并以不泄漏内存的方式进行操作?

有人有什么想法吗?

1 个答案:

答案 0 :(得分:0)

啊,我想我找到了答案,但如果有人知道更好的方法,我可以接受建议:

public static ReadOnlyReactiveProperty<Feature> GetRunningFeature(IEnumerable<Feature> features)
        {
            return Observable.Create<Feature>(obs =>
                {
                    var disposables = new CompositeDisposable();

                    foreach (var feature in features)
                        feature.IsRunning.Subscribe(_ =>
                                obs.OnNext(features.First(f => f.IsRunning.Value)))
                            .AddTo(disposables);

                    return Disposable.Create(() => disposables.Dispose());
                })
                .ToReadOnlyReactiveProperty();
        }