All Projects → Runjuu → mst-effect

Runjuu / mst-effect

Licence: MIT license
💫 Designed to be used with MobX-State-Tree to create asynchronous actions using RxJS.

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to mst-effect

Mobx State Tree
Full-featured reactive state management without the boilerplate
Stars: ✭ 6,317 (+33147.37%)
Mutual labels:  state-management, mobx, observable, mst, mobx-state-tree
Redux Most
Most.js based middleware for Redux. Handle async actions with monadic streams & reactive programming.
Stars: ✭ 137 (+621.05%)
Mutual labels:  redux-observable, rxjs, observable, asynchronous-programming
Bach
Compose your async functions with elegance.
Stars: ✭ 117 (+515.79%)
Mutual labels:  stream, promise, observable
mutable
State containers with dirty checking and more
Stars: ✭ 32 (+68.42%)
Mutual labels:  state-management, mobx, observable
micro-observables
A simple Observable library that can be used for easy state management in React applications.
Stars: ✭ 78 (+310.53%)
Mutual labels:  state-management, mobx, observable
mst-persist
Persist and hydrate MobX-state-tree stores (in < 100 LoC)
Stars: ✭ 75 (+294.74%)
Mutual labels:  mobx, mst, mobx-state-tree
ngx-mobx
Mobx decorators for Angular Applications
Stars: ✭ 14 (-26.32%)
Mutual labels:  rxjs, state-management, mobx
Rxviz
Rx Visualizer - Animated playground for Rx Observables
Stars: ✭ 1,471 (+7642.11%)
Mutual labels:  rxjs, stream, observable
Angular1 Async Filter
Angular2 async pipe implemented as Angular 1 filter to handle promises & RxJS observables
Stars: ✭ 59 (+210.53%)
Mutual labels:  rxjs, promise, observable
rxact
Rxact is an observable application management for Javascript app
Stars: ✭ 21 (+10.53%)
Mutual labels:  rxjs, stream, observable
Marble
Marble.js - functional reactive Node.js framework for building server-side applications, based on TypeScript and RxJS.
Stars: ✭ 1,947 (+10147.37%)
Mutual labels:  rxjs, stream, observable
React Eva
Effects+View+Actions(React distributed state management solution with rxjs.)
Stars: ✭ 121 (+536.84%)
Mutual labels:  rxjs, mobx, observable
data-flow
frontend data flow explored in React
Stars: ✭ 19 (+0%)
Mutual labels:  redux-observable, rxjs, mobx
Cra Boilerplate
Up to date: This project is an Create React App - v2.1.1 boilerplate with integration of Redux, React Router, Redux thunk & Reactstrap(Bootstrap v4)
Stars: ✭ 87 (+357.89%)
Mutual labels:  redux-observable, rxjs
Types First Ui
An opinionated framework for building long-lived, maintainable UI codebases
Stars: ✭ 114 (+500%)
Mutual labels:  redux-observable, rxjs
Rxloop
rxloop = Redux + redux-observable (Inspired by dva)
Stars: ✭ 44 (+131.58%)
Mutual labels:  redux-observable, rxjs
Stuhome
📱 An iOS client for https://bbs.uestc.edu.cn/ written in react-native, redux and redux-observable.
Stars: ✭ 241 (+1168.42%)
Mutual labels:  redux-observable, rxjs
Rxjs Websockets
A very flexible and simple websocket library for rxjs
Stars: ✭ 248 (+1205.26%)
Mutual labels:  redux-observable, rxjs
vuse-rx
Vue 3 + rxjs = ❤
Stars: ✭ 52 (+173.68%)
Mutual labels:  rxjs, state-management
mobx-router5
Router5 integration with mobx
Stars: ✭ 22 (+15.79%)
Mutual labels:  mobx, observable

mst-effect

GitHub license NPM version Bundle size Coverage Status Github discussions

mst-effect is designed to be used with MobX-State-Tree to create asynchronous actions using RxJS. In case you haven't used them before:

MobX-State-Tree is a full-featured reactive state management library that can structure the state model super intuitively.
RxJS is a library for composing asynchronous and event-based programs that provides the best practice to manage async codes.

If you are still hesitant about learning RxJS, check the examples below and play around with them. I assure you that you'll be amazed by what it can do and how clean the code could be.

Already using MobX-State-Tree? Awesome! mst-effect is 100% compatible with your current project.

Examples

Installation

mst-effect has peer dependencies of mobx, mobx-state-tree and rxjs, which will have to be installed as well.

Using yarn:
yarn add mst-effect
Or via npm:
npm install mst-effect --save

Basics

effect is the core method of mst-effect. It can automatically manage subscriptions and execute the emitted actions. For example:

import { types, effect, action } from 'mst-effect'
import { map, switchMap } from 'rxjs/operators'

const Model = types
  .model({
    value: types.string,
  })
  .actions((self) => ({
    fetch: effect<string>(self, (payload$) => {
      function setValue(value: string) {
        self.value = value
      }

      return payload$.pipe(
        switchMap((url) => fetch$(url)),
        map((value) => action(setValue, value)),
      )
    }),
  }))

Import location

As you can see in the example above, types need to be imported from mst-effect(Why?).

The definition of the effect

The first parameter is the model instance, as effect needs to unsubscribe the Observable when the model is destroyed.

The second parameter, a factory function, can be thought of as the Epic of redux-observable. The factory function is called only once at model creation. It takes a stream of payloads and returns a stream of actions. — Payloads in, actions out.

Finally, effect returns a function to feed a new value to the payload$. In actual implementation code, it's just an alias to subject.next.

What is action?

action can be considered roughly as a higher-order function that takes a callback function and the arguments for the callback function. But instead of executing immediately, it returns a new function. Action will be immediately invoked when emitted.

function action(callback, ...params): EffectAction {
  return () => callback(...params)
}

API Reference

👾 effect

effect is used to manage subscriptions automatically.

type ValidEffectActions = EffectAction | EffectAction[]

type EffectDispatcher<P> = (payload: P) => void

function effect<P>(
  self: AnyInstance,
  fn: (payload$: Observable<P>) => Observable<ValidEffectActions>,
): EffectDispatcher<P>

payload$ emits data synchronously when the function returned by the effect is called. The returned Observable<ValidEffectActions> will automatically subscribed by effect

👾 dollEffect

type ValidEffectActions = EffectAction | EffectAction[]

type DollEffectDispatcher<P, S> = <SS = S>(
  payload: P,
  handler?: (resolve$: Observable<S>) => Observable<SS>,
) => Promise<SS>

type SignalDispatcher<S> = (value: S) => void

function dollEffect<P, S>(
  self: AnyInstance,
  fn: (
    payload$: Observable<P>,
    signalDispatcher: SignalDispatcher<S>,
  ) => Observable<ValidEffectActions>,
): DollEffectDispatcher<P, S>

dollEffect is almost identical with effect. The primary difference is DollEffectDispatcher will return a Promise which is useful when you want to report some message to the caller. The Promise will fulfill when SignalDispatcher being invoked (example). Also, you can use the handler to control when and what the Promise should resolve (example).

👾 signal

export function signal<P, R = P>(
  self: AnyInstance,
  fn?: (payload$: Observable<P>) => Observable<R>,
): [Observable<R>, (payload: P) => void]

signal is an encapsulation of the Subject. You can use the second parameter to do some processing of the output data.

👾 reaction$

export function reaction$<T>(
  expression: (r: IReactionPublic) => T,
  opts?: IReactionOptions,
): Observable<{ current: T; prev: T; r: IReactionPublic }>

reaction$ encapsulates the reaction method from mobx. When the returned value changes, it will emit the corresponding data to the returned Observable.

Recipes

Error Handling

When an error occurred in Observable, effect will re-subscribe the Observable (will not re-run the factory function). The common practice is to use the catchError operator for error handling. Check fetch data example for more detail.

Cancellation

You can combine signal and takeUntil() operator to cancel an Observable. Check mutually exclusive actions example for more detail.

FAQ

Why we need to import types from mst-effect

Currently, mobx-state-tree does not support modifying the model outside of actions. mst-effect overrides types.model so that the model can be modified in an asynchronous process. Because mst-effect re-export all the variables and types in mobx-state-tree, you can simply change the import location to mst-effect.

- import { types, Instance } from 'mobx-state-tree'
+ import { types, Instance } from 'mst-effect'
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].