Code Monkey home page Code Monkey logo

mst-effect's Introduction

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'

mst-effect's People

Contributors

dependabot[bot] avatar havef avatar runjuu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

joe-sky vitaly-z

mst-effect's Issues

Misleading example, might lead to confusion.

The "handle-user-input" example has the following "gotchas"

  1. The fetch function in utils does a Math.random() to create an error. This is not obvious to someone reading the code afresh, and causes confusion when they, for example, type their own Github account and it creates an error. One can easily get in the. "error" state by typing a non-sensical word for the username, like "asjfkbaskjfbasg"

  2. the promise-to-observable implementation in utils is confusing, and does not cause an error if the API results in an error.

Here is a fork of your example with a much more "idiomatic" Rx fetch that causes predictable errors.
https://codesandbox.io/s/handle-user-input-forked-gcge9?file=/src/app.tsx

Feel free to update your example if you deem this fit.

Thanks a lot for this library, it is really cool and it is one of the major reasons why I switched from pure MobX to full-blown MST.

ignore this

-- accidentally made an issue from wrong account --

Implicit error handling, can we make it optional?

This library "eats up" all the errors of our stream and logs it out to the console.
https://github.com/Runjuu/mst-effect/blob/c96e9235cd8e10ded0d652bd924574d0c8354658/src/effect/utils.ts#L26

Can I try to make a pull request to make this optional somehow? Or are you against making that behaviour optional? I would prefer if the library didn't try to handle any error for me and let me deal with exceptions in my business logic, and cause panics on unhandled exceptions.

感谢 repo, 三个问题

  1. 关于 reaction$
    reaction$ 感觉和 tostream , 再配合个 from 功能差不多
    是不是可以直接用这个官方的维护性更好?

  2. 关于 action 的一些疑问

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)),
      )
    }),
  }))

其中

      function setValue(value: string) {
        self.value = value
      }

这一部分可以写在和 fetch 同级的地方吗? 这样好像方便 compose 一些?

  1. 老实讲, 整个库还是让我有点困惑

https://egghead.io/lessons/react-defining-asynchronous-processes-using-flow
2分51秒的地方
截屏2021-05-21 上午8 56 22
在 getSuggestion 的地方直接使用 rxjs, 在 subscribe 调用下 mst 的 actions 不就可以了? 为何如此大动周折?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.