() let stream = event.Publish str" /> () let stream = event.Publish str" /> () let stream = event.Publish str"/>

How to `Trigger` in Reactive Extension in F#?

121 Views Asked by At

I did this in F# for FRP that works simply as expected:

let print = fun a -> printf "%A\n" a

let event = new Event<_>()
let stream = event.Publish

stream |> Observable.add (fun event -> event |> print)

event.Trigger 5

Although I don't like much about event.publish system, at least, event.Trigger is somewhat straight forward to understand.

Now, I try to get to used to https://reactivex.io/

I have recognized Rx for a long time since its beta release, and I also know this API is very complicated just to do FRP, like with many "rules" like observable / observer and subjectetc., in my view, this is against KISS principle, so haven't touched.

In fact, a weird thing is for an unknown reason, I can't figure out how to do event.Trigger in Rx.

Surely, I googled a lot, and found a little information for this:

RxJS: How would I "manually" update an Observable?

According to this QA, the code for RxJS is

var eventStream = new Rx.Subject();

var subscription = eventStream.subscribe(
   function (x) {
        console.log('Next: ' + x);
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });

var my_function = function() {
  eventStream.next('foo'); 
}

After many trials, I finally discovered that the code below works, with luck

let stream2 = 7 |> Subject.behavior

stream2
|> Observable.map id
|> Observable.subscribe print
|> ignore

stream2.OnNext 99

However, unfortunately, this is only my Guess simply because there's no such a documentation in https://reactivex.io/documentation/subject.html and there is an external documentation http://xgrommx.github.io/rx-book/content/subjects/subject/index.html

The all I know is this code works as intended.

So, my question here is

Is this the only way to "trigger the value" based on the Rx API design?

1

There are 1 best solutions below

10
supertopi On

You seem to undestand Rx basic terms: IObservable and IObserver. These API:s aren't really that complicated. F# makes it even easier since Events implement IObservable out of the box.

It seems that by trigger you mean "make an Observable emit a value" ( OnNext):

  • If your Observable is created from certain events, triggering such an event will produce a value.

  • If you want to programatically produce a value using a Subject is fine. As stated in the documentation you pasted, it implements both IObservable and IObserver. E.g. you can call OnNext and Subscribe for the object.

I suggest you consider if and why you really need to programatically produce a value in the Observable. Usually you don't since Observables are created from event sources outside your code. Some cases justify using a Subject such as writing unit tests.

Related Questions in F#