我正在尝试在几个Observable
上合并多个ReactiveList
来创建ObservableAsPropertyHelper
。
public class Model : ReactiveObject {
ReactiveList<int> IngredientsEntities;
// ...
public int CostOfIngredients(...) { ... }
}
public class ViewModel : ReactiveObject {
public Model Promotion;
private ReactiveList<int> ingredientsQuantities;
private ObservableAsPropertyHelper<int> cost;
public Dictionary<..., ...> Ingredients;
public int Cost {
get { return cost.Value; }
}
public ViewModel() {
// ...
var ingredientsObservables = new[]
{
ingredientsQuantities.ItemChanged.Select(_ => Unit.Default),
ingredientsQuantities.ShouldReset.Select(_ => Unit.Default),
Promotion.IngredientsEntities.ItemChanged.Select(_ => Unit.Default),
Promotion.IngredientsEntities.ShouldReset.Select(_ => Unit.Default),
};
Observable.Merge(ingredientsObservables)
.Select(_ => promotion.CostOfIngredients(Ingredients))
.ToProperty(this, x => x.Cost, out cost);
Observable.Merge(ingredientsObservables)
.Subscribe(_ =>
{
this.Log().Info("Ingredients change detected");
});
}
}
日志消息会触发,但CostOfIngredients
永远不会被调用,cost
仍然是null
。我在这里做错了吗?
编辑:
我修改了ViewModel
,现在可行了:
public class ViewModel : ReactiveObject {
private int cost;
public int Cost {
get { return cost; }
set { this.RaiseAndSetIfChanged(ref cost, value); }
}
// ...
public ViewModel() {
// ...
var ingredientsObservables = new[]
{
ingredientsQuantities.ItemChanged.Select(_ => Unit.Default),
ingredientsQuantities.ShouldReset.Select(_ => Unit.Default),
Promotion.IngredientsEntities.ItemChanged.Select(_ => Unit.Default),
Promotion.IngredientsEntities.ShouldReset.Select(_ => Unit.Default),
};
Observable.Merge(ingredientsObservables)
.Subscribe(_ => Cost = promotion.CostOfIngredients(Ingredients));
}
}
我的理解是Select(_ => Unit.Default)
为Observable
创建了一个永不改变的Unit.Default
,因此永远不会再调用任何Select
。
答案 0 :(得分:3)
我认为您的问题是您使用ItemChanged
- 只有在您启用了项目跟踪时才会触发,并且只有在您的集合中的项目发生更改时才会触发(即myList[3].SomeProperty = "bar";
)。您可能需要Changed
,这将涵盖所有内容。