Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Samples for updating from a future #335

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions samples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ A native application will be created. If you want to test it on mobile, please f
- SingleChildScrollView
- DataTable

### [Delayed update](./delayed_update)
- state with `:watch`

- Updating state from a Future

### [Drawer](./drawer)
- stateless
Expand Down
6 changes: 6 additions & 0 deletions samples/delayed_update/deps.edn
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{:paths ["src"] ; where your cljd files are
:deps {org.clojure/clojure {:mvn/version "1.10.1"}
tensegritics/clojuredart {:local/root "../../"}}
:aliases {:cljd {:main-opts ["-m" "cljd.build"]}}
:cljd/opts {:main sample.delayed-update
:kind :flutter}}
40 changes: 40 additions & 0 deletions samples/delayed_update/src/sample/delayed_update.cljd
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
(ns sample.delayed-update
"Different versions of updating from futures"
(:require ["package:flutter/material.dart" :as m]
[cljd.flutter :as f]))

(defonce my-result (atom ""))

(defn my-delayed-fn
"a sample function that returns a dart future"
[x] (Future/delayed (Duration .seconds 1) (fn [] (str x " is working!"))))

(defn wait-for-result! [] (reset! my-result (await (my-delayed-fn "wait-for-result!"))))

(defn main []
(f/run
(m/MaterialApp
.title "Delayed Update Demo")
.home
(m/Scaffold
.appBar (m/AppBar .title (m/Text "Delayed Update")))
.body
m/Center
(f/widget
:watch [r my-result]
(m/Column .children
[
;; using reset!
(m/ElevatedButton
.child (m/Text "Using reset!")
.onPressed (fn [] (reset! my-result (await (my-delayed-fn "reset!"))) nil))
;; using swap!
;; this is a bit contrived because there's no reason to not use reset! here
(m/ElevatedButton
.child (m/Text "swap")
.onPressed (fn [] (let [v (await (my-delayed-fn "swap!"))] (swap! my-result (fn [_] v))) nil))
;; using a function that swaps out the atom elsewhere
(m/ElevatedButton
.child (m/Text "delayed fn")
.onPressed (fn [] (wait-for-result!) nil))
(m/Text r)]))))