Is there a way to create an RwSignal
from a get signal and a set signal, like the opposite of RwSignal::split
?
#2356
Answered
by
gbj
ChocolateLoverRaj
asked this question in
Q&A
-
I want to "derive" a |
Beta Was this translation helpful? Give feedback.
Answered by
gbj
Feb 23, 2024
Replies: 2 comments 6 replies
-
No. In theory you could recombine a |
Beta Was this translation helpful? Give feedback.
4 replies
Answer selected by
ChocolateLoverRaj
-
Some naive impl is like below: use leptos::{create_effect, prelude::*};
// Here's a hypothetical definition of the `MergedRwSignal` struct.
// You would need to define this struct based on your specific needs and the context you're working with.
pub struct MergedRwSignal<T: 'static> {
getter: Signal<T>,
setter: SignalSetter<T>,
}
impl<T> MergedRwSignal<T> where T: 'static + Clone {
pub fn from(getter: Signal<T>, setter: SignalSetter<T>) -> RwSignal<T> {
let signal = create_rw_signal(getter.get_untracked());
create_effect(move |_| {
let new_value = getter.get();
signal.set(new_value);
});
signal
}
}
#[cfg(test)]
mod tests {
use super::*;
use leptos::*;
#[derive(Clone, Debug, PartialEq)]
struct StructA {
b: StructB,
}
#[derive(Clone, Debug, PartialEq)]
struct StructB {
value: i32,
}
#[test]
fn test_merged_into_rw_signal() {
let runtime = create_runtime();
let signal_a = create_rw_signal(StructA { b: StructB { value: 10 } });
let (read_a, write_a) = slice!(signal_a.b);
let signal_b = MergedRwSignal::from(read_a, write_a);
signal_b.update(|b| { b.value = 11 });
assert_eq!(signal_a.get_untracked().b.value, 11);
runtime.dispose();
}
} RN the two way binding between the parent signal and derived signal is still missing. Will figure it out later.. |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No. In theory you could recombine a
ReadSignal<T>
andWriteSignal<T>
(but only those) into anRwSignal<T>
, but it might fail at runtime.