Is there a way to be notified when a clojure future finishes?

前端 未结 5 1486
鱼传尺愫
鱼传尺愫 2021-02-04 14:56

Is there a way to set a watch on a future so that it triggers a callback when it is done?

something like this?

> (def a (future (Thread/sleep 1000) \"         


        
5条回答
  •  春和景丽
    2021-02-04 15:13

    You can start another task that watches the future and then runs the function. In this case I'll just use another future. Which wraps up nicely into a when-done function:

    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
    

提交回复
热议问题