|
1 | 1 | //! This crate implements request/async computation coalescing. |
2 | 2 | //! |
3 | | -//! The implementation is modified from fasterthanlime's [article on request coalescing in async rust](https://fasterthanli.me/articles/request-coalescing-in-async-rust). |
| 3 | +//! The starting point for this implementation was fasterthanlime's excellent [article on request coalescing in async rust](https://fasterthanli.me/articles/request-coalescing-in-async-rust). |
4 | 4 | //! |
5 | 5 | //! Caching of async computations can be a bit of a tough problem. |
6 | 6 | //! If no cached value is available when we need it, we would want to compute it, often asynchronously. |
7 | 7 | //! This crate helps ensure that this computation doesn't happen more than it needs to |
8 | 8 | //! by avoiding starting new computations when one is already happening. |
9 | 9 | //! Instead, we will subscribe to that computation and work with the result of it as well. |
| 10 | +//! |
| 11 | +//! # Example |
| 12 | +//! |
| 13 | +//! ``` |
| 14 | +//! # fn answer_too_old() -> bool { true } |
| 15 | +//! # fn refresh_answer_timer() {} |
| 16 | +//! use cache_compute::Cached; |
| 17 | +//! |
| 18 | +//! pub async fn get_answer(cached_answer: Cached<u32, ()>) -> u32 { |
| 19 | +//! if answer_too_old() { |
| 20 | +//! cached_answer.invalidate(); |
| 21 | +//! } |
| 22 | +//! |
| 23 | +//! cached_answer.get_or_compute(|| async { |
| 24 | +//! // Really long async computation |
| 25 | +//! // Phew the computer and network sure need a lot of time to work on this |
| 26 | +//! // Good thing we cache it |
| 27 | +//! // ... |
| 28 | +//! // Ok done |
| 29 | +//! // Other calls to get_answer will now also use that same value |
| 30 | +//! // without having to compute it, until it's too old again |
| 31 | +//! refresh_answer_timer(); |
| 32 | +//! Ok(42) |
| 33 | +//! }) |
| 34 | +//! .await |
| 35 | +//! .unwrap() |
| 36 | +//! } |
| 37 | +//! ``` |
10 | 38 |
|
11 | 39 | #![warn(clippy::pedantic)] |
12 | 40 | #![warn(clippy::cargo)] |
@@ -90,7 +118,7 @@ impl<T, E> Clone for Cached<T, E> { |
90 | 118 | } |
91 | 119 | } |
92 | 120 |
|
93 | | -/// An enum representing the state of an instance of [`Cached`]. |
| 121 | +/// An enum representing the state of an instance of [`Cached`], returned by [`Cached::force_recompute`]. |
94 | 122 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
95 | 123 | pub enum CachedState<T> { |
96 | 124 | /// The cache is empty and there is no inflight computation happening. |
|
0 commit comments