F# has a rather nice syntax for events, which can be subscribed to as observables without any custom code for that purpose. I am creating an event that publishes updates to a member variable. I intend to subscribe to this event as an observable, but I want the existing value (which I know exists) to be pushed on subscription. Is this possible and simple to do with the event syntax, or do I need to create a proper observable using e.g. BehaviorSubject?
This depends a lot on how you plan to use it.
When you convert from an event to an observable, the EventArgs are mapped through as the observable's type. With a "standard" event, this won't have a value (EventArgs doesn't carry any information).
However, you can easily use a custom event type, or event violate normal .NET guidelines for events and use the value itself:
let evt = Event<int>()
let obs = evt.Publish :> IObservable<_>
obs |> Observable.add (fun v -> printfn "New value: %d" v)
evt.Trigger 3
evt.Trigger 4
That being said, depending on your use case, you may want to look at Gjallarhorn. This library was specifically designed for tracking changes to mutable values and signaling nicely. It's built around the concept of a "signal", which is an observable that contains a current value. This makes the above concept first class - you can pass something (a signal) that can directly be used as an IObservable whenever needed, but also can always be used to get the underlying, current value. In practice, this dramatically simplifies many use cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With