【发布时间】:2020-08-26 16:43:07
【问题描述】:
使用带有新 Shell 功能的 Xamarin Forms 4.0,我在页面上有一个按钮。让我们将此页面称为 起始页。
当我按下按钮时,用户将使用Shell.Current.GoToAsync 导航到第二页。
当用户稍后导航回起始页时,该按钮现已停用。但为什么呢?
这是视图模型中的代码:
public class SomeViewModel : ReactiveObject
{
private ReactiveCommand<Unit, Unit> _someCommand;
public ReactiveCommand<Unit, Unit> SomeCommand
{
get => _someCommand;
set => this.RaiseAndSetIfChanged(ref _someCommand, value);
}
public SomeViewModel
{
SomeCommand = ReactiveCommand.CreateFromTask<Unit>(async x =>
{
await Shell.Current.GoToAsync("//Root/SomePage");
}).Subscribe();
}
通过反复试验,我找到了解决方案。
具体来说,通过对 SomeCommand 的定义进行如下修改,当用户返回起始页时,按钮将不再被禁用:
[...]
SomeCommand = ReactiveCommand.CreateFromTask<Unit>(async x =>
{
await Task.CompletedTask;
})
.Select(_ => Observable.FromAsync(() => Shell.Current.GoToAsync("//Root/SomePage")}")))
.Concat()
.Subscribe();
[...]
谁能解释这里发生了什么?为什么第一种方法不起作用,为什么第二种方法起作用?在我看来,这两种方法或多或少是相同的。
我正在使用 ReactiveUI 版本 v9.17.4。到目前为止,我只在 iOS 上测试过。
更新:原来是线程问题。
【问题讨论】:
-
您可以使用
CreateFromObservable简化方法二,而不是使用 select 和 stuff。我强烈怀疑你那里发生了线程问题。 -
使用
CreateFromObservable是一个很好的简化,我不知道。但是,与第一种方法一样,按钮变为 disabled 会产生相同的问题,因此它在这里不起作用。我同意线程问题可能是问题所在。我会尝试调查更多。 -
你不需要 .Subscribe();是我刚刚注意到的另一件事
标签: xamarin xamarin.forms xamarin.ios reactiveui