spawn.rs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #![allow(non_snake_case, unused)]
  2. use dioxus::prelude::*;
  3. fn main() {
  4. dioxus::desktop::launch(App);
  5. }
  6. fn App(cx: Scope) -> Element {
  7. // ANCHOR: spawn
  8. let logged_in = use_state(&cx, || false);
  9. let log_in = move |_| {
  10. cx.spawn({
  11. let logged_in = logged_in.to_owned();
  12. async move {
  13. let resp = reqwest::Client::new()
  14. .post("http://example.com/login")
  15. .send()
  16. .await;
  17. match resp {
  18. Ok(_data) => {
  19. println!("Login successful!");
  20. logged_in.set(true);
  21. }
  22. Err(_err) => {
  23. println!(
  24. "Login failed - you need a login server running on localhost:8080."
  25. )
  26. }
  27. }
  28. }
  29. });
  30. };
  31. cx.render(rsx! {
  32. button {
  33. onclick: log_in,
  34. "Login",
  35. }
  36. })
  37. // ANCHOR_END: spawn
  38. }
  39. pub fn Tokio(cx: Scope) -> Element {
  40. let _ = || {
  41. // ANCHOR: tokio
  42. cx.spawn(async {
  43. let _ = tokio::spawn(async {}).await;
  44. let _ = tokio::task::spawn_local(async {
  45. // some !Send work
  46. })
  47. .await;
  48. });
  49. // ANCHOR_END: tokio
  50. };
  51. None
  52. }
  53. pub fn ToOwnedMacro(cx: Scope) -> Element {
  54. let count = use_state(&cx, || 0);
  55. let age = use_state(&cx, || 0);
  56. let name = use_state(&cx, || 0);
  57. let description = use_state(&cx, || 0);
  58. let _ = || {
  59. // ANCHOR: to_owned_macro
  60. use dioxus::core::to_owned;
  61. cx.spawn({
  62. to_owned![count, age, name, description];
  63. async move {
  64. // ...
  65. }
  66. });
  67. // ANCHOR_END: to_owned_macro
  68. };
  69. None
  70. }