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.

One state to one state

Map

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

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:

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

Tuple

productQty$.tuple(productPrice$)

Many states to one state

Combine

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

ConanState.combine(`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

Last updated