F #: do one action only for the first event without changing / locking?

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

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 locks nor variable vars?

+5
source share
1 answer

Here is one way to use 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)) 
+5
source

Source: https://habr.com/ru/post/1262203/


All Articles