Retrieve XDocument only when modified using Rx + WebRequest + XDocument.Load

狂风中的少年 提交于 2019-12-11 05:34:15

问题


I have the following two observables

System.Net.WebRequest req = System.Net.HttpWebRequest.Create("http://test.com/data.xml"); req.Method = "HEAD";

var ob = Observable.FromAsyncPattern(req.BeginGetResponse, req.EndGetResponse);

ob().Select(x => x).Select(x => x.Headers["Last-Modified"]).DistinctUntilChanged(x => x);

Observable .Interval(TimeSpan.FromSeconds(1.0)) .Select(_ => XDocument.Load("http://test.com/data.xml"));

I would like it that the XDocument observable is only executed when "last-modified" header is greater then the previously requested document any ideas?


回答1:


Firstly .Select(x=>x) is a no-op so you can remove that.

I would change the code up a little bit. First lets break it down into its constituent parts:

1) The Timer. Every second poll the server.

var poll = Observable.Interval(TimeSpan.FromSeconds(1));

2) The call to get the header

var lastModified = Observable.FromAsyncPattern(req.BeginGetResponse, req.EndGetResponse).Select(x => x.Headers["Last-Modified"]);

3) The Select to get the Document

.Select(_ => XDocument.Load("http://test.com/data.xml"));

We should be able to compose that nicely:

var lastModified = from interval in Observable.Interval(TimeSpan.FromSeconds(1))
           from response in Observable.FromAsyncPattern(req.BeginGetResponse, req.EndGetResponse)
           select response.Headers["Last-Modified"];

var data = lastModified.DistinctUntilChanged().Select(_ => XDocument.Load("http://test.com/data.xml"));

data.Subscribe(dataXml=> 
   {
       Console.WriteLine("Data has changed!");
       Console.WriteLine(datXml);
   });

Cavet I just typed that straight into the browser. I would be amazing if it compiles.



来源:https://stackoverflow.com/questions/9161364/retrieve-xdocument-only-when-modified-using-rx-webrequest-xdocument-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!