core-async 2024-07-22

Hi, I'm pretty new at using core.async and I'm trying to implement "long touch/press" event detection using alts! and timeout in Clojurescript. This is what I've got so far and it seems to be working but I'm wondering if there is a better way of doing it. In particular I'm worried about the timeout channel firing every 500ms in the go-loop even when the user is not doing anything. Any tips would be appreciated.

(def touch-event (atom nil))

(def touchstart-ch (chan))
(def touchend-ch (chan))

(.addEventListener js/document "touchstart" (fn [e] (put! touchstart-ch e)))
(.addEventListener js/document "touchend" (fn [e] (put! touchend-ch e)))

(go-loop []
  (let [[key ch] (alts! [touchstart-ch
                         touchend-ch
                         (timeout 500)])]
    (condp = ch
      touchstart-ch (reset! touch-event key)
      touchend-ch (reset! touch-event nil)
      (when-not (nil? @touch-event)
        (println "LONG TOUCH EVENT DETECTED!")
        (reset! touch-event nil))))
  (recur))

I wouldn't worry too much about the timeout channel firing every 500ms from a performance perspective, but I would refactor it from a logical perspective. For long presses, I would break up the go loop as follows: • wait for touch start event • after a touch start event occurs, start a loop that listens for a timeout, a touch start or a touch end, updating its state as necessary. This loop should break and return either a long press, or a long press cancel. • go back to waiting for a touch start event.

Thank you for taking the time to reply. I will try to refactor it and post a solution once I get it to work.