101*_*ris 2 system.reactive reactiveui xamarin.forms
我试图将我的头围绕在最近从6.5.2更新到7.0的reactiveUI上,并且似乎包含了一些关于ReactiveCommand的重大变化.
EG以前的工作:
在ViewModel中:
public ReactiveCommand<Unit> DoLogin;
...
DoLogin = ReactiveCommand.CreateAsyncTask(
async x => {
IsBusy = true;
await Task.Delay(2500);
IsBusy = false;
return Unit.Default;
});
Run Code Online (Sandbox Code Playgroud)
在视图中:
//bind the command
Observable.FromEventPattern(x => loginButton.Clicked += x, x => loginButton.Clicked -= x)
.Subscribe(args => ViewModel.DoLogin.Execute(null));
//do something after the dologin is complete
this.WhenAnyObservable(x => x.ViewModel.DoLogin)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe( x => {
DisplayAlert("login complete", "welcome", "OK");
}
);
Run Code Online (Sandbox Code Playgroud)
但现在在activui 7.0,它是不同的,我不得不做一些改变,我无法让它正常工作:
在ViewModel中:
public ReactiveCommand<Unit, Unit> DoLogin;
...
DoLogin = ReactiveCommand.CreateFromTask(
async x => {
IsBusy = true;
await Task.Delay(2500);
IsBusy = false;
return Unit.Default;
});
Run Code Online (Sandbox Code Playgroud)
在视图中:
//bind the command
Observable.FromEventPattern(x => loginButton.Clicked += x, x => loginButton.Clicked -= x)
.Subscribe(args => ViewModel.DoLogin.Execute());
//do something after the dologin is complete
this.WhenAnyObservable(x => x.ViewModel.DoLogin)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe( x => {
DisplayAlert("login complete", "welcome", "OK");
}
);
Run Code Online (Sandbox Code Playgroud)
命令代码仍然执行,但是WhenANyObservable订阅部分永远不会触发.它从不显示我的DisplayAlert.
我正在使用Xamarin Forms,如果这很重要,但即使在Windows Forms中,我也会遇到相同的行为.
问题是,现在Execute()是一个冷的观察,所以而不是呼唤
ViewModel.DoLogin.Execute()
你得打电话
ViewModel.DoLogin.Execute().Subscribe()
您可以ReactiveCommand在发布文档中了解有关更改的更多信息(ctrl + F"ReactiveCommand is better")
顺便说一下 - 你可以通过在视图中使用绑定来代替拥有它,从而使你的生活变得更轻松Observable.FromEventPattern.有关ReactiveCommand的文档中对此进行了描述.这样你就可以避免Subscribe在另一个Subscribe呼叫中进行呼叫,这是一种代码味道.代码应该与此类似:
this.BindCommand(
this.ViewModel,
vm => vm.DoLogin,
v => v.loginButton);
Run Code Online (Sandbox Code Playgroud)
另一个旁注 - 作为一个可观察的财产ReactiveCommand暴露IsExecuting,所以你可能不需要一个单独的旗帜IsBusy,
| 归档时间: |
|
| 查看次数: |
776 次 |
| 最近记录: |