[][src]Function moxie::state

pub fn state<Output>(
    init: impl FnOnce() -> Output
) -> (Commit<Output>, Key<Output>) where
    Output: 'static, 

Root a state variable at this callsite, returning a Key to the state variable.

Example

use futures::task::waker;
use moxie::{runtime::RunLoop, state, testing::BoolWaker};

// this runtime holds a single state variable
let mut rt = RunLoop::new(|| state(|| 0u64));

let track_wakes = BoolWaker::new();
rt.set_state_change_waker(waker(track_wakes.clone()));

let (first_commit, first_key) = rt.run_once();
assert_eq!(*first_commit, 0, "no updates yet");
assert!(!track_wakes.is_woken(), "no updates yet");

first_key.set(0); // this is a no-op
assert_eq!(*first_key, 0, "no updates yet");
assert!(!track_wakes.is_woken(), "no updates yet");

first_key.set(1);
assert_eq!(*first_key, 0, "update only enqueued, not yet committed");
assert!(track_wakes.is_woken());

let (second_commit, second_key) = rt.run_once(); // this commits the pending update
assert_eq!(*second_key, 1);
assert_eq!(*second_commit, 1);
assert_eq!(*first_commit, 0, "previous value still held by previous pointer");
assert!(!track_wakes.is_woken(), "wakes only come from updating state vars");
assert_eq!(first_key, second_key, "same state variable");

Environment Expectations

This function requires the following types to be visible to illicit::get and will panic otherwise: