dioxus_keys/
lib.rs

1use std::ops::{Deref, DerefMut};
2
3use dioxus_lib::prelude::*;
4
5mod macros;
6
7#[allow(async_fn_in_trait)]
8pub trait DataKey {
9    type Value: Clone + 'static;
10    async fn init();
11    async fn on_change();
12    async fn on_drop();
13    fn read() -> impl Deref<Target = Self::Value> {
14        Self::try_read().unwrap()
15    }
16    fn peek() -> impl Deref<Target = Self::Value> {
17        Self::try_read().unwrap()
18    }
19    fn write() -> impl DerefMut<Target = Self::Value> {
20        Self::try_write().unwrap()
21    }
22    fn try_read() -> Option<impl Deref<Target = Self::Value>>;
23    fn try_peek() -> Option<impl Deref<Target = Self::Value>>;
24    fn try_write() -> Option<impl DerefMut<Target = Self::Value>>;
25}
26
27pub fn use_init_key<K: DataKey<Value = V>, V>(_key: K) -> Resource<()> {
28    use_effect(move || {
29        let val = K::try_read();
30        if val.is_some() {
31            spawn(async { K::on_change().await });
32        }
33    });
34
35    use_drop(|| {
36        spawn(async { K::on_drop().await });
37    });
38
39    use_resource(|| async { K::init().await })
40}