From e3410d5f2fef00558cadce5afb1d69d7260fa831 Mon Sep 17 00:00:00 2001 From: Weihua Lu Date: Tue, 20 Jul 2021 14:32:18 +0800 Subject: [PATCH] core async debounce --- src/main/frontend/extensions/zotero.cljs | 22 +++++++++++--------- src/main/frontend/extensions/zotero/api.cljs | 21 ++++++++++++++++++- 2 files changed, 32 insertions(+), 11 deletions(-) diff --git a/src/main/frontend/extensions/zotero.cljs b/src/main/frontend/extensions/zotero.cljs index 0b314ebc96..e9dd63a8ae 100644 --- a/src/main/frontend/extensions/zotero.cljs +++ b/src/main/frontend/extensions/zotero.cljs @@ -1,5 +1,5 @@ (ns frontend.extensions.zotero - (:require [cljs.core.async :refer [! go chan]] [clojure.string :as str] [frontend.extensions.zotero.api :as api] [frontend.extensions.zotero.handler :as zotero-handler] @@ -38,18 +38,18 @@ (let [[term set-term!] (rum/use-state "") [search-result set-search-result!] (rum/use-state []) [search-error set-search-error!] (rum/use-state nil) - [is-searching set-is-searching!] (rum/use-state false)] + [is-searching set-is-searching!] (rum/use-state false) + term-chan (chan) + debounce-chan (api/debounce term-chan 500)] (rum/use-effect! (fn [] - (let [do-search (fn [] (when-not (str/blank? term) - (go - (let [result (! term-chan (util/evalue e))))}] [:div (map diff --git a/src/main/frontend/extensions/zotero/api.cljs b/src/main/frontend/extensions/zotero/api.cljs index 3eacb8f864..a7d8a77a2b 100644 --- a/src/main/frontend/extensions/zotero/api.cljs +++ b/src/main/frontend/extensions/zotero/api.cljs @@ -1,6 +1,7 @@ (ns frontend.extensions.zotero.api (:require [cljs-http.client :as http] - [cljs.core.async :refer [go ! go-loop timeout close! chan alt!]] [camel-snake-kebab.core :as csk] [camel-snake-kebab.extras :as cske] [frontend.util :as util])) @@ -14,6 +15,24 @@ :type :user :type-id 8234867}) +;; taken from https://github.com/metosin/metosin-common/blob/master/src/cljc/metosin/core/async/debounce.cljc +(defn debounce + "Creates a channel which will change put a new value to the output channel + after timeout has passed. Each value change resets the timeout. If value + changes more frequently only the latest value is put out. + When input channel closes, the output channel is closed." + [in ms] + (let [out (chan)] + (go-loop [last-val nil] + (let [val (if (nil? last-val) (! out val) (recur nil)))))) + out)) + ;; "/users/475425/collections?v=3" (defn get* ([config api]