Composing State

Introduction

We advocate for creating atomic state and to compose new state when you need to.

There are several composition operations that you can perform and that we will see below.

One key aspect of composing state is that it returns another ConanState, which you can compose again.

Inception!

One state to one state

Map

We can derive one state into a new one using ConanState.map:

Js
Js
productQty$.map((productQty)=>productQty.qty)
productPrice$.map((price)=>price.priceUsd)

Filter

We can filter 1 state into a new one using ConanState.filter:

productQty$.filter((productQty) => productQty.qty % 2 === 0)
productQty$.filter((productQty)=>productQty.qty % 2 !== 0)

Two states to one state

Merge

We can merge 2 states into 1 using ConanState.merge:

Js
Js
productQty$.merge(productPrice$, (productQty, productPrice)
=> productQty && productPrice ? productQty.qty * productPrice.priceUsd : 0)

Tuple

Js
Js
productQty$.tuple(productPrice$)

Many states to one state

Combine

We can combine N states into a new one using ConanState.combine:

Js
Ts
Js
ConanState.combine(`combine`, {
price: productPrice$,
qty: productQty$
})
Ts
ConanState.combine<CombinedObject>(
`combine`,
{
price: productPrice$,
qty: productQty$
}
)

Examples

You can navigate these examples in this sandbox:

Composing State + Dependency Injection

Our dependency injection lets you describe atomic and composed state such that from the point of view of their consumers, they would not know (and won't care) wether if it is atomic state or not.

Check out our dependency Injection for more details

Demo