Skip to content

Commit 601952d

Browse files
committed
feat(hooks): Add use_coroutine_with_sender
Adds a new `use_coroutine_with_sender`, which is equivalent to `use_coroutine`, but also receives a sender in the init function. Motivation: More complex coroutines often need to send messages to themselves, for example inside futures to update the state.
1 parent eef4db6 commit 601952d

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

packages/hooks/src/use_coroutine.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,27 @@ where
8989
})
9090
}
9191

92+
/// Same as [`use_coroutine`] but also provides the sender to the init function.
93+
pub fn use_coroutine_with_sender<M, G, F>(mut init: G) -> Coroutine<M>
94+
where
95+
M: 'static,
96+
G: FnMut(UnboundedReceiver<M>, UnboundedSender<M>) -> F + 'static,
97+
F: Future<Output = ()> + 'static,
98+
{
99+
let mut tx_copy_value = use_hook(|| CopyValue::new(None));
100+
101+
let future = use_future(move || {
102+
let (tx, rx) = futures_channel::mpsc::unbounded();
103+
tx_copy_value.set(Some(tx.clone()));
104+
init(rx, tx)
105+
});
106+
107+
use_context_provider(|| Coroutine {
108+
tx: tx_copy_value,
109+
future,
110+
})
111+
}
112+
92113
/// Get a handle to a coroutine higher in the tree
93114
/// Analogous to use_context_provider and use_context,
94115
/// but used for coroutines specifically

0 commit comments

Comments
 (0)