urx by example
Before diving deeper, let's accomplish a small victory with a simple, end-to-end practical walkthrough. In this section, we will build an urx-based React component that sums two numbers and displays the result.
#
Build a Stream SystemLet's start by translating the requirements to a stream system.
In this case, the system consist of two input streams (a
and b
), and one output stream - sum
.
For the initial version, a
and b
can start with default values of 0
.
sumSystem
is the implementation of our sum logic - it constructs the necessary input and
output streams and wires up the relationships between them using the pipe
and combineLatest
transformers and the map
operator.
We also converted the resulting aPlusB
emitter into a stateful stream, so that it always emits a value.
#
Testing a SystemLet's poke the resulting system to get a feeling of how it works. We will import init
, subscribe
, and publish
actions.
In a production project, this should be part of our unit test suite.
The above snippet will call the subscription (console.log
) three times - with 0
, 5
, and 12
.
#
System to React ComponentNext, we will expose our system as a React component. As a twist,
our component will accept the a
as a component property, while b
is going to come from an user input,
from an UI rendered by a child component.
#
Putting it all TogetherThe final step is to render the resulting components. To demonstrate how the SumComponent handles the change of the a
property,
we will wire it up to an input type="range"
.
And, that's it! below, you can find the complete source - open it in CodeSandbox and tweak some of it for more interactive learning.