I have several calls that must be executed sequentially. Consider an IService that has a Query and Load method. The request contains a list of widgets, and the load is a default widget. Therefore, my service looks like this.
void IService.Query(Action<IEnumerable<Widget>,Exception> callback); void IService.Load(Action<Widget,Exception> callback);
With that in mind, here is an approximate sketch of a view model:
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; }
What I would like to do is simplify the sequential workflow of calling the request, and then by default. Perhaps the best way to do this is nested in lambda expressions, as I have shown, but I decided there could be a more elegant way with Rx. I do not want to use Rx for the sake of Rx, but if this allows me to organize the logic above, so it is easier to read / maintain in the method, I will use it. Ideally, something like:
Observable.Create( ()=>firstAction(), ()=>secondAction()) .Subscribe(action=>action(),error=>{ throw error; });
Using a streaming library, I would do something like:
Service.Query(list=>{result=list}; yield return 1; ProcessList(result); Service.Query(widget=>{defaultWidget=widget}; yield return 1; CurrentWidget = defaultWidget;
This makes it much more obvious that the workflow is sequential and eliminates nesting (the output is part of an asynchronous enumerator and are boundaries that are locked until the results return).
Something like that would make sense to me.
So the gist of the question is: Am I trying to put a square anchor in a circular hole, or is there a way to override nested asynchronous calls using Rx?
asynchronous silverlight system.reactive
Jeremy likness
source share