Skip to content

Commit

Permalink
[n.debug] Refactor safe-for-ui and fix its interaction with on-ui
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-yakushev committed Feb 3, 2015
1 parent 931405d commit b2d6e41
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 23 deletions.
28 changes: 14 additions & 14 deletions src/clojure/neko/debug.clj
Expand Up @@ -20,6 +20,8 @@
([key]
`(get all-activities ~key)))

;;; Exception handling

;; This atom stores the last exception happened on the UI thread.
;;
(def ^:private ui-exception (atom nil))
Expand All @@ -37,22 +39,20 @@
"Returns an uncaught exception happened on UI thread."
[] @ui-exception)

(defmacro catch-all-exceptions [func]
(defmacro safe-for-ui
"A conditional macro that will protect the application from crashing
if the code provided in `body` crashes on UI thread in the debug
build. If the build is a release one returns `body` in a `do`-form."
[& body]
(if (:neko.init/release-build *compiler-options*)
`(~func)
`(try (~func)
(catch Throwable e#
(handle-exception-from-ui-thread e#)))))
`(do ~@body)
`(try ~@body
(catch Throwable e# (handle-exception-from-ui-thread e#)))))

(defn safe-for-ui*
"Wraps the given function inside a try..catch block and notify user
using a Toast if an exception happens."
"Wraps the given zero-argument function in `safe-for-ui` call and returns it,
without executing."
[f]
(catch-all-exceptions f))
(fn [] (safe-for-ui (f))))


(defmacro safe-for-ui
"A conditional macro that will protect the application from crashing
if the code provided in `body` crashes on UI thread in the debug
build. If the build is a release one returns `body` as is."
[& body]
`(safe-for-ui* (fn [] ~@body)))
17 changes: 8 additions & 9 deletions src/clojure/neko/threading.clj
Expand Up @@ -28,19 +28,18 @@
(identical? (Thread/currentThread)
(.getThread ^Looper (Looper/getMainLooper))))

(defn on-ui*
"Runs the given nullary function on the UI thread. If this function is
called on the UI thread, it will evaluate immediately."
[f]
(if (on-ui-thread?)
(f)
(.post (Handler. (Looper/getMainLooper)) (fn [] (safe-for-ui (f))))))

(defmacro on-ui
"Runs the macro body on the UI thread. If this macro is called on the UI
thread, it will evaluate immediately."
[& body]
`(on-ui* (fn [] ~@body)))
`(if (on-ui-thread?)
(safe-for-ui ~@body)
(.post (Handler. (Looper/getMainLooper)) (fn [] (safe-for-ui ~@body)))))

(defn on-ui*
"Functional version of `on-ui`, runs the nullary function on the UI thread."
[f]
(on-ui (f)))

(defn ^{:deprecated "3.1.0"} post*
"Causes the function to be added to the message queue. The function will
Expand Down

0 comments on commit b2d6e41

Please sign in to comment.