Merge pull request #2865 from mkane0814/feat/add-map-and-then-for-resource

feat: add Resouce::map and Resouce::and_then
This commit is contained in:
Greg Johnston 2024-08-23 17:30:57 -04:00 committed by GitHub
commit d3707d9b88
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -129,6 +129,14 @@ where
}
}
#[track_caller]
pub fn map<U>(&self, f: impl FnOnce(&T) -> U) -> Option<U>
where
T: Send + Sync + 'static,
{
self.data.try_with(|n| n.as_ref().map(f))?
}
/// Re-runs the async function with the current source data.
pub fn refetch(&self) {
*self.refetch.write() += 1;
@ -172,6 +180,24 @@ where
}
}
impl<T, E, Ser> ArcResource<Result<T, E>, Ser>
where
Ser: Encoder<Result<T, E>> + Decoder<Result<T, E>>,
<Ser as Encoder<Result<T, E>>>::Error: Debug,
<Ser as Decoder<Result<T, E>>>::Error: Debug,
<<Ser as Decoder<Result<T, E>>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
<Ser as Encoder<Result<T, E>>>::Encoded: IntoEncodedString,
<Ser as Decoder<Result<T, E>>>::Encoded: FromEncodedStr,
T: Send + Sync + 'static,
E: Send + Sync + Clone + 'static,
{
#[track_caller]
pub fn and_then<U>(&self, f: impl FnOnce(&T) -> U) -> Option<Result<U, E>> {
self.map(|data| data.as_ref().map(f).map_err(|e| e.clone()))
}
}
impl<T> ArcResource<T, JsonSerdeCodec>
where
JsonSerdeCodec: Encoder<T> + Decoder<T>,
@ -675,12 +701,36 @@ where
}
}
pub fn map<U>(&self, f: impl FnOnce(&T) -> U) -> Option<U> {
self.data
.try_with(|n| n.as_ref().map(|n| Some(f(n))))?
.flatten()
}
/// Re-runs the async function with the current source data.
pub fn refetch(&self) {
self.refetch.try_update(|n| *n += 1);
}
}
impl<T, E, Ser> Resource<Result<T, E>, Ser>
where
Ser: Encoder<Result<T, E>> + Decoder<Result<T, E>>,
<Ser as Encoder<Result<T, E>>>::Error: Debug,
<Ser as Decoder<Result<T, E>>>::Error: Debug,
<<Ser as Decoder<Result<T, E>>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
<Ser as Encoder<Result<T, E>>>::Encoded: IntoEncodedString,
<Ser as Decoder<Result<T, E>>>::Encoded: FromEncodedStr,
T: Send + Sync,
E: Send + Sync + Clone,
{
#[track_caller]
pub fn and_then<U>(&self, f: impl FnOnce(&T) -> U) -> Option<Result<U, E>> {
self.map(|data| data.as_ref().map(f).map_err(|e| e.clone()))
}
}
impl<T, Ser> IntoFuture for Resource<T, Ser>
where
T: Clone + Send + Sync + 'static,