I have an Observable<WebResponse>
(WebResponse
implements IDisposable
)
responseObservable
.Where(webResponse => webResponse.ContentType.StartsWith("text/html"))
.Select(webResponse => webResponse.ContentLength)
.Run()
(Ignore the pointle开发者_StackOverflow中文版ssness of the query!)
so, I'm discarding WebResponse
instances without calling Dispose
on them. This seems bad.
More abstractly: If I have an Observable<IDisposable>
, how do I deal with the disposal of generated items?
Assuming that you have a method WebResponse CreateMyWebResponse()
use Observable.Using
like this:
var responseObservable = Observable.Using(() => CreateMyWebResponse(), Observable.Return);
Change the Where
and Do
bits to something like
.Do(webResponse => {
if (webResponse.ContentType.StartsWith("text/html"))
ProcessAndDispose(webResponse);
else
webResponse.Dispose(); })
perhaps?
EDIT
Based on your edit, how about
.Select(webResponse => {
int r = -1;
if (webResponse.ContentType.StartsWith("text/html"))
r = webResponse.ContentLength;
webResponse.Dispose();
return r; })
.Where(i => i != -1)
now? This would generalize into something like
FilterProjectDispose(e, pred, proj) {
e.Select(x => {
using(x) {
if (pred(x)) return Some(proj(x));
else return None; }})
.Where(x => x.IsSome)
.Select(x => x.Value)
}
assuming Some
/None
as in F# (I am apparently starting to forget my C#).
精彩评论