pub struct View<T> { /* private fields */ }
Expand description
Extracts a view to a sub-element of the global state indicated by the path.
The type of the sub-element is given by the type parameter T.
The View
extractor expects that the location pointed by the Job path
exists and is deserializable into T. If the value may not exist (or is null),
then make sure to use View<Option<T>>
.
§Example
use mahler::{
extract::View,
task::{Handler, create, update, with_io, IO},
worker::{Worker, Ready}
};
use serde::{Serialize, Deserialize};
#[derive(Serialize,Deserialize)]
struct SystemState {/* ... */};
fn foo_bar(mut view: View<i32>) -> IO<i32> {
// view can be dereferenced into the given type
// and is guaranteed to exist at this point
if *view < 5 {
*view += 1;
}
with_io(view, |view| async {
// do something with view at runtime
Ok(view)
})
}
fn create_counter(mut view: View<Option<i32>>) -> IO<Option<i32>> {
if view.is_none() {
// Initialize with default value if it doesn't exist
*view = Some(0);
}
with_io(view, |view| async {
// do something with view at runtime
Ok(view)
})
}
let worker: Worker<SystemState, Ready> = Worker::new()
.job("/{foo}/{bar}", create(create_counter))
.job("/{foo}/{bar}", update(foo_bar))
.initial_state(SystemState {/* ... */})
.unwrap();
§Errors
Initializing the extractor will fail if the path assigned to the job cannot be resolved or the
value pointed by the path cannot be deserialized into type <T>
Trait Implementations§
Source§impl<T, E> From<View<T>> for IO<T, E>
Convert a View<T>
directly into an IO operation.
impl<T, E> From<View<T>> for IO<T, E>
Convert a View<T>
directly into an IO operation.
This creates an IO operation that immediately succeeds with the given view, without performing any actual I/O. This is useful for bailing out early in jobs before creating the effectful computation.
§Examples
fn plus_one(mut view: View<u32>, Target(tgt): Target<u32>) -> IO<u32> {
if *view >= tgt {
// exit early if we already reached the target
return view.into();
}
with_io(view, |view| async {
// do some async work
Ok(view)
})
// increase the target after the IO operation
// terminates (at runtime)
.map(|mut counter| {
*counter = *counter + 1;
counter
})
}
Source§impl<T: DeserializeOwned> FromSystem for View<T>
impl<T: DeserializeOwned> FromSystem for View<T>
Auto Trait Implementations§
impl<T> Freeze for View<T>where
T: Freeze,
impl<T> RefUnwindSafe for View<T>where
T: RefUnwindSafe,
impl<T> Send for View<T>where
T: Send,
impl<T> Sync for View<T>where
T: Sync,
impl<T> Unpin for View<T>where
T: Unpin,
impl<T> UnwindSafe for View<T>where
T: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more