2016-11-24 87 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