|
1 | 1 | pub mod bind_for_each;
|
2 | 2 | pub mod for_each;
|
| 3 | +pub mod for_each_async; |
3 | 4 | pub mod signal_stream;
|
4 | 5 |
|
5 | 6 | use std::cell::{Ref, RefMut};
|
6 | 7 |
|
7 |
| -use futures_core::Stream; |
| 8 | +use futures_core::{Future, Stream}; |
8 | 9 |
|
9 | 10 | use crate::{
|
10 | 11 | borrow_mut_guard::BorrowMutGuard, until_change::UntilChange, Path, ReferencePath, Trackable,
|
@@ -286,6 +287,41 @@ pub trait PathExt: Path {
|
286 | 287 | for_each::ForEach::new(self, self.until_change(), closure)
|
287 | 288 | }
|
288 | 289 |
|
| 290 | + /// Execute the given async function (a function returning Future) |
| 291 | + /// with the data as argument. Repeat every time the data changes. |
| 292 | + /// |
| 293 | + /// If the async function is still executing when the data changes, |
| 294 | + /// the execution is canceled (by dropping the Future) so that the new |
| 295 | + /// one can start. |
| 296 | + /// |
| 297 | + /// The return future finishes when the data couldn't be accessed |
| 298 | + /// (when [borrow_opt][PathExt::borrow_opt] returns None). |
| 299 | + /// |
| 300 | + /// ``` |
| 301 | + /// # use x_bow::{Path, PathExt}; |
| 302 | + /// # async fn example(path_to_url: &impl Path<Out = String>) { |
| 303 | + /// # struct ui_element; |
| 304 | + /// # impl ui_element { |
| 305 | + /// # fn set_text(&self, t: &str) {} |
| 306 | + /// # } |
| 307 | + /// # async fn fetch_content(url: &String) -> String { |
| 308 | + /// # todo!(); |
| 309 | + /// # } |
| 310 | + /// // when the URL changes, fetch the content and set the text |
| 311 | + /// path_to_url.for_each_async(|url: &String| async move { |
| 312 | + /// let content = fetch_content(url).await; |
| 313 | + /// ui_element.set_Text(&content); |
| 314 | + /// }).await; |
| 315 | + /// # } |
| 316 | + /// ``` |
| 317 | + #[must_use = "the returned Future is lazy; await it to make it do work"] |
| 318 | + fn for_each_async<F: Future<Output = ()>, C: FnMut(&Self::Out) -> F>( |
| 319 | + &self, |
| 320 | + closure: C, |
| 321 | + ) -> for_each_async::ForEachAsync<'_, Self, F, C> { |
| 322 | + for_each_async::ForEachAsync::new(self, self.until_change(), closure) |
| 323 | + } |
| 324 | + |
289 | 325 | /// For making a two-way binding.
|
290 | 326 | ///
|
291 | 327 | /// The given `on_change` function is called once in the beginning and
|
|
0 commit comments