I have a problem where some objects change their properties based on some internal logic. For the sake of simplicity, let's imagine an object RandomSource
that has a public Int
field named Value
. The object has its own thread and, sometimes, it updates the Value
field.
Now, other objects in the system are interested in being notified that the Value
was updated. In C#, I could define a companion delegate that objects subscribe, and which it is raised when the property is updated.
My question is thus the following: how do I do this in Scala? Which is the most "idiomatic" solution?
Observers are still pretty standard, also known as Publisher/Listener. You can roll your own, or you could use some actor-based solution if you want async notifications.
On the functional side, this stuff is more often done through functional reactive frameworks. There's Naftoli's Reactive, but Akka also provides a Dataflow
, which amounts to very much the basic concepts.
Beyond these, this is a field of research on the evolution of Scala, so you can be sure you'll see more of them.
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