views:

50

answers:

2

I have an Observable<WebResponse> (WebResponse implements IDisposable)

responseObservable
    .Where(webResponse => webResponse.ContentType.StartsWith("text/html"))
    .Select(webResponse => webResponse.ContentLength)
    .Run()

(Ignore the pointlessness 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?

+1  A: 

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#).

Brian
@Brian, I've edited my question slightly to reflect better what I'm actually doing. I'm really wondering if there's a pattern for dealing with this kind issue. I've looked at Observable.Using, but I don't really get it.
spender
+1  A: 

Assuming that you have a method WebResponse CreateMyWebResponse() use Observable.Using like this:

var responseObservable = Observable.Using(() => CreateMyWebResponse(), Observable.Return);
PL