Motoko | RxMo | Reactive programming

Made @ Anvil Research

I’ve just started a new library RxMo and published its first working version. Currently has
Observable, Subject, pipe, of, map, first, concatAll, mergeMap.

Why

Business processes are asynchronous. Smart contracts in IC dealing with business logic could benefit a great deal from reactive programming which is especially good with complex async logic.
Orthogonal persistence & Heartbeat make it even more powerful. Reactively programmed business logic should be a significant differentiator for IC.

Besides business logic: If Ethereum programs collaboration is like a lego pyramid. IC programs collaboration is more like async hypergraph and can also benefit from reactive programming.

This pattern will also be an interesting combination Motoko | Jazz heartbeat

Notes: Testing with moc -r could benefit from async delay mock or heartbeat so deploying won’t be needed to test asynchronous execution.

Example

The real-world examples will be coming soon, meanwhile:

pipe2(
    of<Text>(["A","B","C"]),
    mergeMap<Text,Text>( func(x) { 
        pipe2(
            of<Nat>([1,2,3,4,5,6]),
            map<Nat, Text>( func (i) {
                x # debug_show(i);
            })
        );
    }, 1)
).subscribe( {
    next = func (v) {
        Debug.print(v);
    };
    complete = func () {
        Debug.print("complete");
    }
});

Outputs:

A1 A2 A3 A4 A5 A6 B1 B2 B3 B4 B5 B6 C1 C2 C3 C4 C5 C6

To help you visualize reactive programming : RxMarbles: Interactive diagrams of Rx Observables

Repo

9 Likes

Look like someone else used RxJS a bit too :wink:. Interesting initiative :+1:

Looking at the spinet in your README, the first thing that comes to my mind is: do I need to unsubscribe?

1 Like

I think It’s best to get it working as close to RxJS as possible (which I used for reference) so all the documentation can be reused :slight_smile:
About unsubscribe: You can have many Subjects in your smart contracts and subscribe/unsubscribe from them whenever you want.

1 Like

Nice! It can make the jump to Motoko easier for Angular devs, it’s a cool idea.

1 Like

This is very cool and if you got it working with heartbeat it would be great to use it to turn the crank on GitHub - skilesare/pipelinify.mo: Move data chunks between canisters for pushing resources around the IC or just handling multi-step computation that exceeds the cycle limit.

1 Like

I made something closer to a real-world example.

The whole example is @ the playground here: Motoko Playground - DFINITY

I need something more complicated to showcase its power (to prove it’s viable) … You can still do this without Rx. It will probably take 10 more lines of code.