2. Save an owned snapshot and wait for acknowledgement
The write serialises a snapshot of the current draft. The pending snapshot is separate from the last acknowledged value, so an error cannot turn an unsaved edit into Saved. The switch is disabled while this small operation is pending; callbacks still record the exact snapshot that was sent.
Serialization can fail before the request is queued. The reducer handles that result as well as the asynchronous provider error. Completion actions are unit routing actions: the reducers decode the actual Store result from cx.input, not a placeholder action payload.
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/state.rs","value":"src-state-rs"},{"index":1,"label":"src/app.rs","value":"src-app-rs"}]}
{"id":"fission-tabs-1","index":0,"label":"src/state.rs","value":"src-state-rs"}
use fission::prelude::*;
use fission::core::STORE_SET;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Preferences { pub show_help: bool }
impl Default for Preferences {
fn default() -> Self { Self { show_help: true } }
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Phase { #[default] Idle, Loading, Ready, Saving, Failed }
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PreferencesState {
pub draft: Preferences,
pub saved: Option<Preferences>,
pub phase: Phase,
pub error: Option<String>,
pending: Option<Preferences>,
}
impl GlobalState for PreferencesState {}
fn preferences_key() -> StoreKey<Preferences> {
StoreKey::new("tutorial.android.inspection", "preferences")
}
#[fission_reducer(HydratePreferences)]
pub fn hydrate_preferences(
state: &mut PreferencesState,
cx: &mut ReducerContext<PreferencesState>,
) {
if !matches!(state.phase, Phase::Idle | Phase::Failed) { return; }
state.phase = Phase::Loading;
state.error = None;
let ok = cx.effects.bind(PreferencesExist, reduce_with!(preferences_exist));
let err = cx.effects.bind(PreferencesLoadFailed, reduce_with!(preferences_load_failed));
cx.effects.store().contains(preferences_key()).on_ok(ok).on_err(err);
}
#[fission_reducer(PreferencesExist)]
fn preferences_exist(state: &mut PreferencesState, cx: &mut ReducerContext<PreferencesState>) {
match cx.input.store_contains() {
Some(false) => {
state.draft = Preferences::default();
state.saved = None;
state.phase = Phase::Ready;
}
Some(true) => {
let ok = cx.effects.bind(PreferencesLoaded, reduce_with!(preferences_loaded));
let err = cx.effects.bind(PreferencesLoadFailed, reduce_with!(preferences_load_failed));
cx.effects.store().get(preferences_key()).on_ok(ok).on_err(err);
}
None => {
state.phase = Phase::Failed;
state.error = Some("Store returned no contains result".into());
}
}
}
#[fission_reducer(PreferencesLoaded)]
fn preferences_loaded(state: &mut PreferencesState, cx: &mut ReducerContext<PreferencesState>) {
match cx.input.store_value::<Preferences>() {
Some(Ok(preferences)) => {
state.draft = preferences.clone();
state.saved = Some(preferences);
state.phase = Phase::Ready;
}
Some(Err(error)) => {
state.phase = Phase::Failed;
state.error = Some(error.to_string());
}
None => {
state.phase = Phase::Failed;
state.error = Some("Store returned no preference value".into());
}
}
}
#[fission_reducer(PreferencesLoadFailed)]
fn preferences_load_failed(state: &mut PreferencesState, cx: &mut ReducerContext<PreferencesState>) {
state.phase = Phase::Failed;
state.error = Some(cx.input.store_error()
.map(|error| error.to_string())
.unwrap_or_else(|| "Store returned no failure details".into()));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn startup_does_not_claim_the_default_was_loaded_or_saved() {
let state = PreferencesState::default();
assert_eq!(state.phase, Phase::Idle);
assert!(state.saved.is_none());
}
}
pub fn save_preferences(state: &mut PreferencesState, cx: &mut ReducerContext<PreferencesState>) {
if state.phase != Phase::Ready { return; }
let snapshot = state.draft.clone();
state.pending = Some(snapshot.clone());
state.phase = Phase::Saving;
state.error = None;
let ok = cx.effects.bind(PreferencesSaved, reduce_with!(preferences_saved));
let err = cx.effects.bind(PreferencesSaveFailed, reduce_with!(preferences_save_failed));
match cx.effects.store().set(preferences_key(), &snapshot) {
Ok(effect) => { effect.on_ok(ok).on_err(err); }
Err(error) => {
state.pending = None;
state.phase = Phase::Ready;
state.error = Some(error.to_string());
}
}
}
#[fission_reducer(PreferencesSaved)]
fn preferences_saved(state: &mut PreferencesState, cx: &mut ReducerContext<PreferencesState>) {
state.phase = Phase::Ready;
if cx.input.capability_ok(STORE_SET).is_some() {
if let Some(saved) = state.pending.take() { state.saved = Some(saved); }
} else {
state.pending = None;
state.error = Some("Store returned no save acknowledgement".into());
}
}
#[fission_reducer(PreferencesSaveFailed)]
fn preferences_save_failed(state: &mut PreferencesState, cx: &mut ReducerContext<PreferencesState>) {
state.phase = Phase::Ready;
state.pending = None;
state.error = Some(cx.input.store_error()
.map(|error| error.to_string())
.unwrap_or_else(|| "Store returned no failure details".into()));
}
{"id":"fission-tabs-1","index":1,"label":"src/app.rs","value":"src-app-rs"}
use fission::prelude::*;
use crate::state::{
PreferencesState, Phase, HydratePreferences, hydrate_preferences,
save_preferences,
};
fission_component! {
pub InspectionPreferences<PreferencesState> {}
view(_settings, state, cx) {
let tokens = &cx.view.env().theme.tokens;
let hydrate = with_reducer!(cx.build, HydratePreferences, hydrate_preferences);
} =>
Container(SafeArea(child: Scroll(child:
Container(Column(gap: tokens.spacing.m, children: [
Text(cx.tr("preferences.title")).size(tokens.typography.heading1_size),
if matches!(state.phase, Phase::Idle | Phase::Loading) {
Row(gap: tokens.spacing.s, children: [
Spinner(motion: Some(SpinnerMotion::Default), label: cx.tr("preferences.loading")),
Text(cx.tr("preferences.loading")),
])
} else if state.phase == Phase::Failed {
Column(gap: tokens.spacing.s, children: [
Text(cx.tr("preferences.load_failed")),
Button(
child: Text(cx.tr("preferences.retry")),
key: "retry-hydration",
on_press: hydrate,
).semantics_identifier("preferences.retry"),
])
} else {
Column(gap: tokens.spacing.m, children: [
FormControl(
label: Some(cx.tr("preferences.show_help")),
child: Switch(
checked: state.draft.show_help,
disabled: state.phase == Phase::Saving,
bind(on_toggle): to(state.draft.show_help),
),
),
if state.draft.show_help { Text(cx.tr("preferences.help")) },
Text(cx.tr(if state.saved.as_ref() == Some(&state.draft) {
"preferences.saved"
} else {
"preferences.unsaved"
})),
Button(
child: Text(cx.tr("preferences.save")),
key: "save-preferences",
disabled: state.phase != Phase::Ready || state.saved.as_ref() == Some(&state.draft),
on_press: reduce { save_preferences(state, cx); },
).semantics_identifier("preferences.save"),
if state.phase == Phase::Saving {
Spinner(motion: Some(SpinnerMotion::Default), label: cx.tr("preferences.saving"))
},
])
},
if let Some(error) = &state.error {
Column(gap: tokens.spacing.s, children: [
Text(cx.tr("preferences.error")).color(tokens.colors.error),
Code(text: error.clone()),
])
},
]))
.padding_all(tokens.spacing.l)
.width_length(Length::percent(100.0))
.max_width(720.0),
)))
.height_length(Length::vh(100.0))
}
{"id":"fission-tabs-1"}
Change the switch, save, and wait for Saved. Reload the preview and check that the same value is loaded from that browser origin's real storage. Android uses its own SQLite database; saving in the browser does not alter the phone's preference.
Show the app previewHide the app preview
Show the app preview
Hide the app preview