Skip to content

Instantly share code, notes, and snippets.

@giannissc
Last active February 24, 2024 12:23
Show Gist options
  • Save giannissc/d1f53ebcf19c7eee7f4b52a162d77318 to your computer and use it in GitHub Desktop.
Save giannissc/d1f53ebcf19c7eee7f4b52a162d77318 to your computer and use it in GitHub Desktop.
State Management Patterns (and the Problems they Address) in Druid and Xilem

Types of State

  • Global Scope State = Application Data or Model
  • Local Scope State = UI State / Empemeral State (e.g. animation progress)
  • Inherited Scope State = Shared UI State / Ambient State (e.g. month selection in calendar element)
  • Distributed State (e.g. tab selection shared by tab bar and a tab grid that live in different parts of the view tree)
  • Transient State/Impulse Response (e.g. a button is pressed and a side bar is revealed)

Generic State Access Patterns (aka Global State)

  • Subset: Callback or Adapt
  • Descendent: Lens or Adapt

Xilem

struct AppData
struct SharedState
struct DistributedState

let app_data = AppData{}
let calendar_data = SharedState{}
let tab_data = Arc::new(DistributedState{})


// state = f() - General State Generation Pattern
// state_subset = f(&mut data) - General State Access Pattern
// view = f(state) - General View Generation Pattern

// button(f(&mut state)) - Global Data Access
// calendar(f() -> S, f(state)) - Global and Shared Data Access
// tab_bar(f() -> Arc(S), f(state)) - Global and Distributed Data Access
// tab_grid(f() -> Arc(S), f(state)) - Global and Distributed Data Access

button_view = button(|data| {...}) // Global Scope
calendar_view = calendar(move || {calendar_data ...})

let tab_data_a = tab_data.clone()
let tab_data_b = tab_data.clone()

tab_bar_view = tab_bar(move || {tab_data_a ...})
tab_grid_view = tab_grid(move || {tab_data_b ...})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment