Files
dioxus/packages/hooks/src/use_callback.rs
T
Evan AlmloffandJonathan Kelley baf5a95cae Fix cloned rsx double drop (#2839)
* Implement Rc generational pointers

* Clean up error handling a bit

* start adding tests

* Simplify a few types

* Separate Rc and normal generational boxes

* Add tests for rc drop and read

* Move over the pointer instead of the data in ReadOnlySignal props

* Fix panic on ref drop and release mode builds

* final rc signal cleanup

* use rc generational boxes for event handlers as well

* add a regression test for read only signal cloning

* merge main

---------

Co-authored-by: Jonathan Kelley <jkelleyrtp@gmail.com>
2024-10-14 09:23:09 -07:00

24 lines
970 B
Rust

use dioxus_core::prelude::use_hook;
use dioxus_core::prelude::Callback;
/// Create a callback that's always up to date. Whenever this hook is called the inner callback will be replaced with the new callback but the handle will remain.
///
/// There is *currently* no signal tracking on the Callback so anything reading from it will not be updated.
///
/// This API is in flux and might not remain.
#[doc = include_str!("../docs/rules_of_hooks.md")]
pub fn use_callback<T: 'static, O: 'static>(f: impl FnMut(T) -> O + 'static) -> Callback<T, O> {
let mut callback = Some(f);
// Create a copyvalue with no contents
// This copyvalue is generic over F so that it can be sized properly
let mut inner = use_hook(|| Callback::new(callback.take().unwrap()));
if let Some(callback) = callback.take() {
// Every time this hook is called replace the inner callback with the new callback
inner.replace(Box::new(callback));
}
inner
}