Last active
August 29, 2015 14:14
-
-
Save pbalduino/982ba9e5fc63aa72984b to your computer and use it in GitHub Desktop.
Agent watchers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ;; Primeiro criamos um agent a | |
| (def a (agent 1)) | |
| ;; A função watch deve ter quatro parâmetros: uma chave única, | |
| ;; a referência ao próprio agent, o valor antigo e o valor novo. | |
| (defn a-watch [key ref old new] | |
| (println "Watching" key ref old new)) | |
| ;; vamos criar uma função que dobra o valor recebido e informa | |
| ;; quando está sendo executada | |
| (defn a-double [value] | |
| (println "Changing") | |
| (* value 2)) | |
| ;; vamos associar o watch ao agent. O primeiro parâmetro é o agent, | |
| ;; o segundo é a chave única e o terceiro é a função watcher | |
| (add-watch a :a a-watch) | |
| ;; e agora, ao executar send, vemos a função a-double e o watcher | |
| ;; sendo executados | |
| (send a a-double) | |
| ; #<Agent@676e6c3c: 1>Changing | |
| ; Watching :a #<Agent@676e6c3c: 2> 1 2 | |
| @a | |
| ; 2 | |
| ;; Você pode adicionar quantos watchers quiser, desde que a chave seja única. | |
| (add-watch a :b a-watch) | |
| (send a a-double) | |
| ; Changing | |
| ; Watching :b #<Agent@676e6c3c: 8> 4 8 | |
| ; Watching :a #<Agent@676e6c3c: 8> 4 8 | |
| ; #<Agent@676e6c3c: 4> | |
| ;; A ordem de execução dos watchers não pode ser garantida, já que internamente | |
| ;; eles são armazenados em um hashmap | |
| ;; Para removermos um watcher, basta utilizar remove-watch | |
| (remove-watch a :a) | |
| (send a a-double) | |
| ; Changing | |
| ; Watching :b #<Agent@676e6c3c: 16> 8 16 | |
| ; #<Agent@676e6c3c: 8> | |
| ;; Como um mero detalhe de implementação, podemos ver os watchers relacionados | |
| ;; àquele agent | |
| (.getWatches a) | |
| ; {:b #<user$a_watch user$a_watch@2f16ae4f>} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment