【发布时间】:2010-08-16 22:00:21
【问题描述】:
我有一些必须按顺序执行的调用。考虑一个具有 Query 和 Load 方法的 IService。查询提供了一个小部件列表,加载提供了一个“默认”小部件。因此,我的服务看起来像这样。
void IService.Query(Action<IEnumerable<Widget>,Exception> callback);
void IService.Load(Action<Widget,Exception> callback);
考虑到这一点,下面是视图模型的粗略草图:
public class ViewModel : BaseViewModel
{
public ViewModel()
{
Widgets = new ObservableCollection<Widget>();
WidgetService.Query((widgets,exception) =>
{
if (exception != null)
{
throw exception;
}
Widgets.Clear();
foreach(var widget in widgets)
{
Widgets.Add(widget);
}
WidgetService.Load((defaultWidget,ex) =>
{
if (ex != null)
{
throw ex;
}
if (defaultWidget != null)
{
CurrentWidget = defaultWidget;
}
}
});
}
public IService WidgetService { get; set; } // assume this is wired up
public ObservableCollection<Widget> Widgets { get; private set; }
private Widget _currentWidget;
public Widget CurrentWidget
{
get { return _currentWidget; }
set
{
_currentWidget = value;
RaisePropertyChanged(()=>CurrentWidget);
}
}
}
我想做的是简化调用查询的顺序工作流程,然后是默认的。也许最好的方法是嵌套 lambda 表达式,正如我所展示的,但我认为 Rx 可能有更优雅的方法。我不想为了 Rx 而使用 Rx,但是如果它可以让我组织上面的逻辑以便在方法中更容易阅读/维护,我会利用它。理想情况下,类似:
Observable.Create(
()=>firstAction(),
()=>secondAction())
.Subscribe(action=>action(),error=>{ throw error; });
使用电源线程库,我会做类似的事情:
Service.Query(list=>{result=list};
yield return 1;
ProcessList(result);
Service.Query(widget=>{defaultWidget=widget};
yield return 1;
CurrentWidget = defaultWidget;
这使得工作流是顺序的并且消除了嵌套更加明显(收益是异步枚举器的一部分,并且是在结果返回之前阻塞的边界)。
任何类似的东西对我来说都是有意义的。
所以问题的本质是:我是在尝试将方形钉安装到圆孔中,还是有办法使用 Rx 重新定义嵌套的异步调用?
【问题讨论】:
-
我正在为这个问题寻找类似的东西:stackoverflow.com/questions/3280345/… - 如果您能够以您的经验回答我的问题,我们将不胜感激 =)
-
我正在研究概念证明,以展示聚合多个(不同)服务调用并按顺序执行它们。准备好后会通知您!
标签: silverlight asynchronous system.reactive