Is there a way to get notified when the future of clojure ends?

Is there any way to set the clock in the future so that it will call back when it was done?

something like that?

> (def a (future (Thread/sleep 1000) "Hello World!") > (when-done a (println @a)) ...waits for 1sec... ;; => "Hello World" 
+4
source share
4 answers

You can run another task that keeps track of the future and then runs the function. In this case, I will just use a different future. What complements the β€œwhen-to-do” feature:

 user=> (defn when-done [future-to-watch function-to-call] (future (function-to-call @future-to-watch))) user=> (def meaning-of-the-universe (let [f (future (Thread/sleep 10000) 42)] (when-done f #(println "future available and the answer is:" %)) f)) #'user/meaning-of-the-universe ... waiting ... user=> future available and the answer is: 42 user=> @meaning-of-the-universe 42 
+9
source

For very simple cases: If you do not want to block and do not care about the result, just add a callback to the future definition.

 (future (a-taking-time-computation) (the-callback)) 

If you care about the results, use comp with a callback

 (future (the-callback (a-taking-time-computation))) 

or

 (future (-> input a-taking-time-computation callback)) 

Semantically speaking, the equivalent java code would be:

 final MyCallBack callbackObj = new MyCallBack(); new Thread() { public void run() { a-taking-time-computation(); callbackObj.call(); } }.start() 

In difficult cases, you can see:

https://github.com/ztellman/manifold

https://github.com/clojure/core.async

+2
source

Instead of adding extra time with Thread/Sleep , I use the fact that @future-ref for any reference to the future will wait until the future is done.

 (defn wait-for [futures-to-complete] (every? #(@%) futures-to-complete)) 
0
source

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


All Articles