handling state mutation on reactive programming project reactor - reactive-programming

i have a question regarding updating mutable state on reactive streams. I found the following code:
Mono<Transaction> closeTransaction(Long id) {
return transactionRepository.findById(1L)
.map(transaction -> transaction.setStatus("DONE")
.flatMap(transactionRepository::save);
}
Then, reading some books on functional and reactive programming, i have found that they suggest not mutating data state or doing some side effects activities on reactive primitives such as map. However i have found lot of reactive code written like above code. How should we handle state mutation on reactive frameworks? I'm woking on Java projects with project reactor and it is not clear which primitives should handle with mutable state and which shouldn't.
Thanks,
Jorge

Related

State monad or another functional approach to building object graphs in FRP

I'm developing a functional reactive programming app, in Sodium FRP and Scala, with heavy GUI-based interaction. The challenge is to program the construction of a complex graph with FRP nodes -- event Streams and state Cells. The construction proceeds in order-dependent steps, with the created objects passed on to next steps. Several domain and UI modules are involved. The process is fragile and not very functional.
It seems that the State Monad (SM) could be a good functional alternative. Indeed, several SM applications are not dissimilar to construction of object graphs, eg: https://channel9.msdn.com/Shows/Going+Deep/Brian-Beckman-The-Zen-of-Expressing-State-The-State-Monad, or Breadth-First Search using State monad in Haskell. And yet, my search hasn't produced any uses of SM for objects construction or configuration.
Specifically, I plan to split the FRP graph into subgraphs, and for each define something like
case class ConfigureSubGraph {
inputA: Option[Stream[String]] = None
inputB: Option[Stream[String]] = None
inputC: Option[Cell[String]] = None
...
intermediateOutputs: Option[Cell[DomainEntities]] }
with the fields pre-initialised to None. (Here, Cell and Stream are from SodiumFRP.) This would be "loaded" into a State Monad and incrementally configured.
Could a State Monad work for this? If yes, is there any implementation advice? If not, are there other functional approaches to construction of object graphs (not necessarily FRP)?

Scalaz vs ReactiveX

I´ve been working for a couple years with ReactiveX extension in Java, but now I move to scala, and I´ve seen that many people use the extension ScalaZ to perform more functional programing in Scala.
Is there´s any differences to use ScalaZ extension, or just adapt reactiveX to Scala which I did and I know is playing nice with Scala?.
And after read this blog https://medium.com/#luijar/the-observable-disguised-as-an-io-monad-c89042aa8f31 I though the observable was working as a IO monad as in Scalaz
Regards.
Scalaz and ReactiveX are completely orthogonal to one another.
Scalaz is focused on bringing Category theory à la Haskell to Scala. It brings tons of type classes with Monads and Monoids and other goodies.
ReactiveX on the other hand is more focused on bringing reactive programming concepts to the language. It comes with Observables and Observers.
You can even use RxScala in conjunction with Scalaz! There's a repo called RxScalaz providing some of the typeclass instances of Scalaz for RxScala. Check it out here: https://github.com/everpeace/rxscalaz
If you're happy with "only" using RxScala, then there's no "real" need to accomodate Scalaz into your project.

Dependency injection with Akka

I use Guice in my application quite a lot. Recently i start to learn akka actors and felt like refactoring my application with it.
However upfront i am already wondering how all my guice will work with actors. I went on searching on google and it is kinda a bit messy.
The most up to date docs that i have found on the subject are theses:
http://letitcrash.com/post/55958814293/akka-dependency-injection
http://eng.42go.com/tag/guice/
which do not advocate same thing.
I must confess i still need to read a lot, i am at the beginning of learning akka. I Did few examples and red few things, but i don't want to go to deep into something to realize later that i will have many problems.
So my question is as of today, what is the consensus on how to use Akka Actors with dependency injection.
What kind of injection is possible ? Can we wire actors with object/other actors/....
Can anyway please outline in a concise way something that can help me to understand what is possible and what is the best practices ?
I know you are working in Akka with Guice and Scala, but Typesafe provides a tutorial describing how things work in Akka with Spring and Java. This can provide a good starting point for understanding how dependency injection fits into the Actor lifecycle for your situation.
Meanwhile, here is some sample code from their documentation for using a factory method to inject constructor arguments:
class DependencyInjector(applicationContext: AnyRef, beanName: String) extends IndirectActorProducer {
override def actorClass = classOf[Actor]
override def produce = // obtain fresh Actor instance from DI framework ...
}
val actorRef = system.actorOf(Props(classOf[DependencyInjector], applicationContext, "hello"), "helloBean")
Here are some guidelines compiled by Typesafe on the matter.
Finally, note the following from the documentation:
"When using a dependency injection framework, actor beans MUST NOT have singleton scope."
The latest activator has a tutorial for Akka with Guice.

How to make a code thread safe in scala?

I have a code in scala that, for various reasons, have few lines of code that cannot be accessed by more threads at the same time.
How to easily make it thread-safe? I know I could use Actors model, but I find it a bit too overkill for few lines of code.
I would use some kind of lock, but I cannot find any concrete examples on either google or on StackOverflow.
I think that the most simple solution would be to use synchronized for critical sections (just like in Java). Here is Scala syntax for it:
someObj.synchronized {
// tread-safe part
}
It's easy to use, but it blocks and can easily cause deadlocks, so I encourage you to look at java.util.concurrent or Akka for, probably, more complicated, but better/non-blocking solutions.
You can use any Java concurrency construct, such as Semaphores, but I'd recommend against it, as semaphores are error prone and clunky to use. Actors are really the best way to do it here.
Creating actors is not necessarily hard. There is a short but useful tutorial on actors over at scala-lang.org: http://www.scala-lang.org/node/242
If it is really very simple you can use synchronized: http://www.ibm.com/developerworks/java/library/j-scala02049/index.html
Or you could use some of the classes from the concurrent package in the jdk: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html
If you want to use actors, you should use akka actors (they will replace scala actors in the future), see here: http://doc.akka.io/docs/akka/2.0.1/. They also support things like FSM (Finite State Machine) and STM (Software Transactional Memory).
In general try to use pure 'functions' or methods with immutable data structures that should help with thread safety.

Serialization in Scala / Akka

I am writing a distributed application in Scala that uses Akka actors. I have some data structures that my remote actors happily serialize, send over the wire, and unserialize without any extra help from me.
For logging I would like to serialize a case class containing these objects. I read the serialization docs on the akka project site but am wondering if there an easier way to get this done since Akka apparently knows how to serialize these objects already.
Edit 5 Nov 2011 in response to Viktor's comment
The application is a distributed Markov Decision Process engine.
I am trying to serialize one of these things:
case class POMDPIteration(
observations: Set[(AgentRef, State)],
rewards: Set[(AgentRef, Float)],
actions: Set[(AgentRef, Action)],
state: State
)
here is the definition of AgentRef:
case class AgentRef(
clientManagerID: Int,
agentNumber: Int,
agentType: AgentType
)
Action and AgentType are just type aliases of Symbol
To keep this shorter, the definition of State is here:
https://github.com/ConnorDoyle/EnMAS/blob/master/src/main/scala/org/enmas/pomdp/State.scala
I am successfully sending case classes containing object of type State among remote actors with no problem. I am just wondering if there is a way to get at the serialization routines that Akka uses for my own purposes.
Akka's implicit serialization when doing message passing is easy, but it appears from the docs that asking Akka for a serialized version explicitly is hard. Perhaps I have misunderstood the documentation, or am missing something important.
This is the magic sauce: https://github.com/akka/akka/blob/master/akka-remote/src/main/scala/akka/remote/RemoteTransport.scala