1
0

atom_ref.rs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. use crate::{use_atom_root, AtomId, AtomRef, AtomRoot, Readable};
  2. use dioxus_core::{ScopeId, ScopeState};
  3. use std::{
  4. cell::{Ref, RefCell, RefMut},
  5. rc::Rc,
  6. };
  7. ///
  8. ///
  9. ///
  10. ///
  11. ///
  12. ///
  13. ///
  14. ///
  15. pub fn use_atom_ref<T: 'static>(cx: &ScopeState, atom: AtomRef<T>) -> &UseAtomRef<T> {
  16. let root = use_atom_root(cx);
  17. cx.use_hook(|_| {
  18. root.initialize(atom);
  19. UseAtomRef {
  20. ptr: atom.unique_id(),
  21. root: root.clone(),
  22. scope_id: cx.scope_id(),
  23. value: root.register(atom, cx.scope_id()),
  24. }
  25. })
  26. }
  27. pub struct UseAtomRef<T> {
  28. ptr: AtomId,
  29. value: Rc<RefCell<T>>,
  30. root: Rc<AtomRoot>,
  31. scope_id: ScopeId,
  32. }
  33. impl<T: 'static> UseAtomRef<T> {
  34. pub fn read(&self) -> Ref<T> {
  35. self.value.borrow()
  36. }
  37. pub fn write(&self) -> RefMut<T> {
  38. self.root.force_update(self.ptr);
  39. self.value.borrow_mut()
  40. }
  41. pub fn write_silent(&self) -> RefMut<T> {
  42. self.root.force_update(self.ptr);
  43. self.value.borrow_mut()
  44. }
  45. pub fn set(&self, new: T) {
  46. self.root.force_update(self.ptr);
  47. self.root.set(self.ptr, new);
  48. }
  49. }
  50. impl<T> Drop for UseAtomRef<T> {
  51. fn drop(&mut self) {
  52. self.root.unsubscribe(self.ptr, self.scope_id)
  53. }
  54. }