2016-11-24 90 views
2

我试图围绕reactiveUI,最近从6.5.2更新到7.0,似乎包括一些关于ReactiveCommand的重大变化。ReactiveUI 7.0,ReactiveCommand,订阅永远不会触发?

EG这个曾经工作:

在视图模型:

public ReactiveCommand<Unit> DoLogin; 

    ... 

    DoLogin = ReactiveCommand.CreateAsyncTask( 
    async x => { 
     IsBusy = true; 
     await Task.Delay(2500); 
     IsBusy = false; 
     return Unit.Default; 
    }); 

在查看:

 //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"); 
     } 
    ); 

但是现在reactiveui 7.0,它是不同的,我不得不做出一些更改,我无法正常工作:

in ViewModel:

public ReactiveCommand<Unit, Unit> DoLogin; 
    ... 
    DoLogin = ReactiveCommand.CreateFromTask( 
    async x => { 
     IsBusy = true; 
     await Task.Delay(2500); 
     IsBusy = false; 
     return Unit.Default; 
    }); 

在查看:

 //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"); 
     } 
    ); 

命令代码仍然被执行,但WhenANyObservable订阅部分永远不会触发。它从不显示我的DisplayAlert。

我正在使用Xamarin Forms,如果这很重要,但即使在Windows窗体中我也会得到相同的行为。

回答

6

的问题是,现在Execute()是一个寒冷的观察到的,所以不是调用

ViewModel.DoLogin.Execute()

你必须调用

ViewModel.DoLogin.Execute().Subscribe()

你可以阅读更多关于ReactiveCommand变化release docs(ctrl + F“ReactiveCommand is Better”)

顺便说一句 - 通过在您的视图中使用绑定来代替Observable.FromEventPattern,您可能会让您的生活更轻松。这在docs about ReactiveCommand中描述。通过这种方式,您将避免在另一个Subscribe调用中出现Subscribe调用,这是一种代码异味。该代码应与此类似:

this.BindCommand(
    this.ViewModel, 
    vm => vm.DoLogin, 
    v => v.loginButton); 

另一个阿里纳斯 - ReactiveCommand暴露IsExecuting作为观察特性,所以你也许并不需要一个单独的标志IsBusy

+1

是的,伟大的。我设法解决了这个问题。现在它变得更清洁了。在尝试学习某些我不明白的东西时遇到了困难,同时语法也发生了变化! – 101chris