F#: only do one action once for the first event, without mutability/locking?

大憨熊 提交于 2019-12-10 15:45:00

问题


I have this code that downloads a file and tells me in the console how big is the file:

use webClient = new WebClient()

let lockObj = new Object()
let mutable firstProgressEvent = true
let onProgress (progressEventArgs: DownloadProgressChangedEventArgs) =
    lock lockObj (fun _->
        if (firstProgressEvent) then
            let totalSizeInMB = progressEventArgs.TotalBytesToReceive / 1000000L
            Console.WriteLine ("Starting download of {0}MB...", totalSizeInMB)
        firstProgressEvent <- false
    )

webClient.DownloadProgressChanged.Subscribe onProgress |> ignore
let task = webClient.DownloadFileTaskAsync (uri, Path.GetFileName(uri.LocalPath))
task.Wait()

Is there a way to do the same, but using neither locking nor mutable vars?


回答1:


Here is one way using the Reactive Extensions:

open System.Net
open FSharp.Control

let webClient = new WebClient()
let disposable = 
  Observable.take 1 webClient.DownloadProgressChanged 
  |> Observable.subscribe (fun progress -> printfn "%A" (progress.TotalBytesToReceive))


来源:https://stackoverflow.com/questions/41439213/f-only-do-one-action-once-for-the-first-event-without-mutability-locking

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