2012-04-25 47 views
1

在我的应用程序中,我使用Web请求调用链从网上获取数据。即从一个请求的结果我会发送其他请求等。但是当我处理Web请求时,只有父请求正在处理。另外两个请求仍在运行。如何我可以取消所有这些请求在Rx如何在Windows Phone 7中处理嵌套的Rx Web请求调用

+1

请发表您的代码。使用一个简单的'SelectMany'查询可以在一行中解决您的问题,但很难解释如何在不引用代码的情况下将其应用于您的情况。 – Enigmativity 2012-04-26 03:02:51

回答

2

您的订阅终止一切,你要么不能打破单子,或者你需要确保你进入IDisposable模式工作。

为了保持单子(即坚持IObservables):

var subscription = initialRequest.GetObservableResponse() 
    .SelectMany(initialResponse => 
    { 
     // Feel free to use ForkJoin or Zip (intead of Merge) to 
     // end up with a single value 
     return secondRequest.GetObservableResponse() 
      .Merge(thirdRequest.GetObservableResponse()); 
    }) 
    .Subscribe(subsequentResponses => { }); 

为了使用IDisposable模式:

var subscription = initialRequest.GetObservableResponse() 
    .SelectMany(initialResponse => 
    { 
     return Observable.CreateWithDisposable(observer => 
     { 
      var secondSubscription = new SerialDisposable(); 
      var thirdSubscription = new SerialDisposable(); 

      secondSubscription.Disposable = secondRequest.GetObservableResponse() 
       .Subscribe(secondResponse => 
       { 
        // Be careful of race conditions here! 

        observer.OnNext(value); 
        observer.OnComplete(); 
       }); 

      thirdSubscription.Disposable = thirdRequest.GetObservableResponse() 
       .Subscribe(thirdResponse => 
       { 
        // Be careful of race conditions here! 
       }); 

      return new CompositeDisposable(secondSubscription, thirdSubscription); 
     }); 
    }) 
    .Subscribe(subsequentResponses => { }); 
1

一个approah是通过使用TakeUntil扩展方法如here所述。在你的情况下,将此方法作为参数的事件可能是父请求抛出的某个事件。

如果您可以向我们展示一些代码,我们可以更具体地面对问题。

问候,