Skip to main content

aureole_reactive/
stored.rs

1use std::fmt;
2use std::marker::PhantomData;
3use std::rc::Rc;
4
5use crate::runtime::{DefinedAt, HandleMarker, Kind, NodeId, Value, read_value, try_read_value, with_runtime};
6
7/// 存值:不需要响应的数据(`Rc` 包着的服务、配置、缓存)放在运行时里,换一个 `Copy` 的句柄。
8///
9/// 和 [`Signal`](crate::Signal) 一样归创建时的作用域、句柄能随意被闭包捕获,所以不用为每个闭包先克隆一份;
10/// 不同的是读不订阅、写不通知,值变了界面也不会更新(要更新就用信号)。作用域释放后再读会 panic,
11/// 确实可能已经释放时用 [`StoredValue::try_with`]。
12pub struct StoredValue<T> {
13    id: NodeId,
14    defined: DefinedAt,
15    marker: HandleMarker<T>,
16}
17
18/// 创建存值,等同于 [`StoredValue::new`]
19#[track_caller]
20pub fn stored_value<T: 'static>(value: T) -> StoredValue<T> {
21    StoredValue::new(value)
22}
23
24impl<T: 'static> StoredValue<T> {
25    /// 创建存值,归当前作用域所有
26    #[track_caller]
27    pub fn new(value: T) -> Self {
28        let value: Value = Rc::new(value);
29        let id = with_runtime(|rt| rt.create(Kind::Signal, Some(value), None));
30        Self { id, defined: DefinedAt::here(), marker: PhantomData }
31    }
32
33    /// 借用读取(不订阅)。闭包里可以 [`StoredValue::set`]:手里的还是读开始时的值
34    #[track_caller]
35    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
36        read_value(with_runtime(|rt| rt.snapshot(self.id)), self.defined, f)
37    }
38
39    /// 读取一份(不订阅)
40    #[track_caller]
41    pub fn get(&self) -> T
42    where
43        T: Clone,
44    {
45        self.with(T::clone)
46    }
47
48    /// 和 [`StoredValue::with`] 一样借用读取,已经释放时是 `None`
49    #[track_caller]
50    pub fn try_with<R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
51        try_read_value(with_runtime(|rt| rt.snapshot(self.id)), self.defined, f)
52    }
53
54    /// 换成新的值(不通知谁)。已经释放时什么都不做
55    pub fn set(&self, value: T) {
56        with_runtime(|rt| rt.set(self.id, value));
57    }
58
59    /// 原地修改(不通知谁)。已经释放时什么都不做;正在读它(在它自己的 [`StoredValue::with`] 闭包里)时 panic
60    pub fn update(&self, f: impl FnOnce(&mut T)) {
61        with_runtime(|rt| rt.update(self.id, f));
62    }
63
64    /// 释放。用于随数据创建的存值,删除数据时调用;平时交给作用域
65    pub fn dispose(self) {
66        with_runtime(|rt| rt.dispose_later(self.id));
67    }
68}
69
70impl<T> Clone for StoredValue<T> {
71    fn clone(&self) -> Self {
72        *self
73    }
74}
75
76impl<T> Copy for StoredValue<T> {}
77
78impl<T> PartialEq for StoredValue<T> {
79    fn eq(&self, other: &Self) -> bool {
80        self.id == other.id
81    }
82}
83
84impl<T> Eq for StoredValue<T> {}
85
86impl<T> fmt::Debug for StoredValue<T> {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        f.debug_tuple("StoredValue").field(&self.id).finish()
89    }
90}