How to manage state without using Subject or imperative manipulation in a simple RxJS example?

前端 未结 1 1077
夕颜
夕颜 2020-12-28 18:40

I have been experimenting with RxJS for two weeks now, and although I love it in principle I just cannot seem to find and implement the correct pattern for managing state. A

相关标签:
1条回答
  • 2020-12-28 18:59

    I think you already found a good example with : http://jsbin.com/redeko/edit?js,output.

    You take issue with the fact that this implementation

    explicitly uses a state object for addition and removal of items.

    However, thas is exactly the good practice you are looking for. If you rename that state object viewModel for example, it might be more apparent to you.

    So what is state?

    There will be other definitions but I like to think of state as follows:

    • given f an impure function, i.e. output = f(input), such that you can have different outputs for the same input, the state associated to that function (when it exists) is the extra variable such that f(input) = output = g(input, state) holds and g is a pure function.

    So if the function here is to match an object representing a user input, to an array of todo, and if I click add on a todo list with already have 2 todos, the output will be 3 todos. If I do the same (same input) on a todo list with only one todo, the output will be 2 todos. So same input, different outputs.

    The state here that allows to transform that function into a pure function is the current value of the todo array. So my input becomes an add click, AND the current todo array, passed through a function g which give a new todo array with a new todo list. That function g is pure. So f is implemented in a stateless way by making its previously hidden state explicit in g.

    And that fits well with functional programming which revolves around composing pure functions.

    Rxjs operators

    • scan

    So when it comes to state management, with RxJS or else, a good practice is to make state explicit to manipulate it.

    If you turn the output = g(input, state) into a stream, you get On+1 = g(In+1, Sn) and that's exactly what the scan operator does.

    • expand

    Another operator which generalizes scan is expand, but so far I had very little use of that operator. scan generally does the trick.

    Sorry for the long and mathy answer. It took me a while to get around those concepts and that's the way I made them understandable for me. Hopefully it works for you too.

    0 讨论(0)
提交回复
热议问题