I want to return an HttpResponseMessage, which implements IDisposable, within a Result (or any other discriminated union). However, since Result itself is not IDisposable, I can't use! it like I would for the disposable object itself. What do I do? Can I implement my own DU called DisposableResult that implements IDisposable itself?
Below is an example of what I mean. crawlStuff asynchronously returns Result<HttpResponseMessage, string>. I can't use! the result, leading to a memory leak unless I manually release it.
open System.Net.Http
let crawlStuff (client : HttpClient) : Async<Result<HttpResponseMessage, string>> =
async {
// res is HttpResponseMessage which implements IDisposable
let! res = client.GetAsync("https://ifconfig.me") |> Async.AwaitTask
return
if res.IsSuccessStatusCode then
Ok res
else
Error "Something wrong"
}
async {
use client = new HttpClient()
// Memory leak because result it could carry HttpResponseMessage.
// I want to use! here, but can't because Result<> is not IDisposable
let! response = crawlStuff client
printfn "%A" response
} |> Async.RunSynchronously