If you use something like Websockets for communication, depending on the library you are using they may or may not include some way to handle callback events. To handle this (or any other case were message callbacks are not a native option) this library provides some helpers.
The idea is to send a message providing some
ID, and then wait for a response message to come, the response will include the same
ID from the request, so they match.
This process happens in three main steps:
Once we send a message requiring a callback, create something to get notified once the response arrives
If you read a message that wants a response, create and send the response message
Listen to message responses on the event entry point
This mechanism assumes your message are maps.
1, you create a function that wraps whatever your transmit function is:
(defn send-message! [msg]
; this will check if the message has a request-id, and if so will create a channel
; that will have data available once the message is replied
Then, wrap your read side with the
(defn handle-message [msg]
; this will fire the handler when the message contains ::wap/response-id, otherwise
; it lets the message flow
(if-not (wap/capture-response! msg)
In your handle, to reply a message, to this:
(defn some-handler [msg]
(send-message! (wap/reply-message msg) "reply value"))
And finally, to issue a request and wait for the callback:
(let [res (<? (send-message! (assoc msg ::wap/request-id (wap/random-request-id))))]
(print "Response: " res)))
await! helper has a built-in timeout mechanism, the default wait time is 5s.