Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for effects with custom runtimes #3469

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion leptos_macro/src/view/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1651,7 +1651,7 @@ pub(crate) fn ident_from_tag_name(tag_name: &NodeName) -> Ident {
.path
.segments
.iter()
.last()
.next_back()
.map(|segment| segment.ident.clone())
.expect("element needs to have a name"),
NodeName::Block(_) => {
Expand Down
102 changes: 102 additions & 0 deletions reactive_graph/src/effect/effect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ use any_spawner::Executor;
use futures::StreamExt;
use or_poisoned::OrPoisoned;
use std::{
future::Future,
mem,
pin::Pin,
sync::{atomic::AtomicBool, Arc, RwLock},
};

Expand Down Expand Up @@ -196,6 +198,57 @@ impl Effect<LocalStorage> {
Self { inner }
}

/// Creates a new effect, which runs once on the next “tick”, and then runs again when reactive values
/// that are read inside it change.
///
/// This spawns a task on the local thread using
/// [`spawn_local`](any_spawner::Executor::spawn_local). For an effect that can be spawned on
/// any thread, use [`new_sync`](Effect::new_sync).
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Docs should probably be updated to

  1. Note that this allows you to pass in a runtime, and
  2. Update the new_sync x 2 here to new_sync_with_runtime

pub fn new_with_runtime<T, M>(
mut fun: impl EffectFunction<T, M> + 'static,
pass_to_rt: impl FnOnce(Pin<Box<dyn Future<Output = ()> + 'static>>),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd suggest a name like spawn here rather than pass_to_rt as that's the phrase we tend to use for "spawn a task" elsewhere

I think the signature can be something like

    pub fn new_with_runtime<T, M, F, Fut>(
        mut fun: impl EffectFunction<T, M> + 'static,
        pass_to_rt: F
    ) -> Self 
    where 
        T: 'static,
        F: FnOnce(Fut) + 'static,
        Fut: Future<Output = ()>

if you want to avoid the Pin<Box<_>> here

) -> Self
where
T: 'static,
{
let inner = cfg!(feature = "effects").then(|| {
let (mut rx, owner, inner) = effect_base();
let value = Arc::new(RwLock::new(None::<T>));
let mut first_run = true;

let task = Box::pin({
let value = Arc::clone(&value);
let subscriber = inner.to_any_subscriber();

async move {
while rx.next().await.is_some() {
if subscriber
.with_observer(|| subscriber.update_if_necessary())
|| first_run
{
first_run = false;
subscriber.clear_sources(&subscriber);

let old_value =
mem::take(&mut *value.write().or_poisoned());
let new_value = owner.with_cleanup(|| {
subscriber.with_observer(|| {
run_in_effect_scope(|| fun.run(old_value))
})
});
*value.write().or_poisoned() = Some(new_value);
}
}
}
});
pass_to_rt(task);

ArenaItem::new_with_storage(Some(inner))
});

Self { inner }
}

/// A version of [`Effect::new`] that only listens to any dependency
/// that is accessed inside `dependency_fn`.
///
Expand Down Expand Up @@ -414,6 +467,55 @@ impl Effect<SyncStorage> {
Self { inner }
}

/// See [`Self::new_sync`]. This function additional allows for a custom
/// runtime to be supplied by the caller.
pub fn new_sync_with_runtime<T, M>(
mut fun: impl EffectFunction<T, M> + Send + Sync + 'static,
pass_to_rt: impl FnOnce(
Pin<Box<dyn Future<Output = ()> + Send + Sync + 'static>>,
),
) -> Self
where
T: Send + Sync + 'static,
{
let inner = cfg!(feature = "effects").then(|| {
let (mut rx, owner, inner) = effect_base();
let mut first_run = true;
let value = Arc::new(RwLock::new(None::<T>));

let task = {
let value = Arc::clone(&value);
let subscriber = inner.to_any_subscriber();

Box::pin(async move {
while rx.next().await.is_some() {
if subscriber
.with_observer(|| subscriber.update_if_necessary())
|| first_run
{
first_run = false;
subscriber.clear_sources(&subscriber);

let old_value =
mem::take(&mut *value.write().or_poisoned());
let new_value = owner.with_cleanup(|| {
subscriber.with_observer(|| {
run_in_effect_scope(|| fun.run(old_value))
})
});
*value.write().or_poisoned() = Some(new_value);
}
}
})
};
pass_to_rt(task);

ArenaItem::new_with_storage(Some(inner))
});

Self { inner }
}

/// Creates a new effect, which runs once on the next “tick”, and then runs again when reactive values
/// that are read inside it change.
///
Expand Down