以下是我处理这种情况的方法。你需要一个类似于这个的行为,只有当设置了一个特定的已知值时,它才会调用你的命令。当您的视图模型它发生 -
// Only invoke the command when the property matches a known value that can't happen through normal execution
this.WhenAnyValue(vm => vm.SomeProperty)
.Where(sp => sp == null)
.Throttle(TimeSpan.FromSeconds(.25), TaskPoolScheduler.Default)
.Do(_ => Debug.WriteLine($"Refresh the List"))
.InvokeCommand(GetList)
.DisposeWith(SubscriptionDisposables);
在你的构造函数结束时,设置SomeProperty与已知值
this.SomeProperty = null; // or some value that makes sense
在这种情况下,你不需要手动触发命令OnAppearing是第一次构建的,直到ViewModel被丢弃并重新创建之后才会被再次执行。 对我来说这似乎有些黑客,所以我希望更聪明,更经验丰富的RxUI奇才会加入,但它可以完成工作。
如果您希望保留OnAppearing调用,您也可以通过设置ReactiveCommand的canExecute属性并为您的PullToRefresh操作使用完全不同的ReactiveCommand来处理此问题(即使两个命令的行为都相同) 。在这种情况下,首先填充列表后,您希望canExecute始终为false,因此即使用户返回页面时也不会触发初始填充。
var isInitialized = this.WhenAnyValue(vm => vm.IsInit).Select(_ => _ == false).DistinctUntilChanged();
InitList = ReactiveCommand.CreateFromTask(_ =>
{
// get list
}, isInitialized);
RefreshList = ReactiveCommand.CreateFromTask(_ =>
{
// essentially the same as InitList, but with different/no canExecute parameters
});
InitList.ObserveOn(RxApp.MainThreadScheduler).Subscribe(result =>
{
this.IsInit = false
}).DisposeWith(SubscriptionDisposables);
这里的缺点是,很明显,你有一些逻辑复制
来源
2017-08-18 14:35:34
Joe
你试过'FromEventPattern(...出现......)。拿(1)'? – Dorus
为了让它也听按钮的点击,你可以用这个可观察的元素“合并”。 – Dorus
是的@Dorus,它没有工作。不过,这是一个好主意。 – fferegrino