Subscription without any parameters - scala

I need to write some RxScala code that creates an Observable from a text field in Scala Swing.
After looking on Github, I wrote this code, which seems to work:
def textValues: Observable[String] = Observable.create[String](observer => {
observer.onNext(field.text)
Subscription()
})
Where field.text gives the current state of the text from that field.
I don't understand this line however:
Subscription()
What is this Subscription useful for? It doesn't take any parameters so I'm assuming that it can't be used to unsubscribe from the observable I created, since it doesn't even reference this observable.
So what is a Subscription() good for?
Why doesn't it take any parameters?

First, to answer your question about the line:
Subscription()
It creates an empty subscription, that is, a subscription which does nothing when unsubscribe is called on it (instead of deregistering the event listener).
Second, note that you're using the "old fashioned" way of creating Observables:
#deprecated("Use [[Observable.apply]] instead", "0.26.2")
def create[T](f: Observer[T] => Subscription): Observable[T]
The new way is this one:
def apply[T](f: Subscriber[T] => Unit): Observable[T]
It corresponds to RxJava's Observable.create.
If you want to register unsubscribe actions with this method, you should use Subscriber.add(Subscription).
And third, let me point you to RxSwing, which defines all kinds of Observables for Swing Events, so that you don't have to re-implement them yourself. It's written in Java, but it's easily compatible with Scala, as you can see, for instance, in this example.

Related

empty in Monix Task

Project Reactor has something like Mono.empty[T]() which can be handled in special circumstances where you do not have anything when it is evaluated. Is there something similar in Monix Task?
def getItemFromList[T](inp: Mono[List[T]]): Mono[T] = {
val moList = inp.defaultIfEmpty(List[T]())
moList.flatMap[T]((list: List[T]) => {
if (list.isEmpty) Mono.empty[T]()
else Mono.just(list.head)
})
}
Here I am trying to lift an item from a list of items, where the list can be non existent while reading from the db. I do not want to send something like Mono.just(List()) as that will require me to add another empty/null check on the db call side.
Monix' Task and Project Reactor's Mono differ in terms of logic.
While Mono can complete to "nothing", Task can only complete to "something" or never complete at all (which makes a lot more sense).
To correctly describe your problem with Task, you will have to use something like Task[Option[T]] and then return Task.now(None) or move over to Monix' Observable, which models a stream of elements (that can also be empty).

Event Logger Pattern in Scala

All of our backend services is written in Scala. We mostly write pure functional Scala using Cats.
I am trying to figure out if there is a design pattern in Cats or Scala in general that I can use to design a EventLogger.
This eventLogger should collects "events" (simple key values) as the request flows through the logic. At the end of the request, I want to write the collected events to data store. We already have a "context" implicit parameter that gets passed to all the methods. I could add this EventLogger to my Context class and it would have access to the event logger from most parts of my code. Now I am trying to figure out how to design the eventLogger itself, without using a mutable collection.
I have used to akka actors to collect states in the past to manage mutating states. I would prefer not to introduce Akka into our classpath just for this.
As #AndreyTyukin suggests, Writer would work well here.
You could do something like:
object EventLogger {
type Event = (String, String)
def log(event: Event): Writer[Vector[Event], Unit] =
Writer.tell(Vector(event))
}
And then you could use it like this:
// Example usage
for {
something <- Writer.value(myFunc(arg))
_ <- EventLogger.log("function_finished" -> "myFunc")
somethingElse <- Writer.value(myFunc2(arg2))
_ <- EventLogger.log("function_finished" -> "myFunc2")
} yield combine(something, somethingElse)
At the end of this, you'll have some kind of Writer[Vector[Event], ?] value where the ? might be a value you're interested in and the Vector[Event] is all of your Event log data ready for you to do something with.
Also usually Writer won't be the only container you want to use. You probably want to investigate Monad Transformers to stack up containers or something like Eff.

When should I make methods with implicit argument in Scala?

I made codes using play framework in scala which look like the following:
object Application extends Controller {
def hoge = Action( implicit request =>
val username = MyCookie.getName.get
Ok("hello " + username)
}
}
object MyCookie {
def getName( implicit request: RequestHeader ) = {
request.cookies.get("name").map(_.value)
}
}
I got a code review from my coworker. He said this code is not readable because of implicit parameter. I couldn't reply to his opinion. So could you tell me what is the best way to use implicit parameters? When should I use implicit parameters?
You should use implicit parameters when there is almost always a "right" way to do things, and you want to ignore those details almost all the time; or when there often is no way to do things, and the implicits provide the functionality for those things that work.
For an example of the first case, in scala.concurrent.Future, almost every method takes an implicit ExecutionContext. You almost never care what your ExecutionContext is from call to call; you just want it to work. But when you need to change the execution context you can supply it as an explicit parameter.
For an example of the second case, look at the CanBuildFroms in the collections library. You cannot build anything from anything; certain capabilities are supplied, and the lack of an implicit that, say, lets you package up a bunch of Vector[Option[String]]s into a HashSet[Char] is one major way to keep the library powerful and flexible yet sane.
You are doing neither: apparently you're just using it to save a little typing in one spot at the expense of the other spot. And, in this case, in doing so you've made it less obvious how things work, as you have to look all over the place to figure out where that implicit request actually gets used. If you want to save typing, you're much better off using short variable names but being explicit about it:
Action{ req => val name = MyCookie.getName(req).get; Ok("hello "+name) }

Configuration data in Scala -- should I use the Reader monad?

How do I create a properly functional configurable object in Scala? I have watched Tony Morris' video on the Reader monad and I'm still unable to connect the dots.
I have a hard-coded list of Client objects:
class Client(name : String, age : Int){ /* etc */}
object Client{
//Horrible!
val clients = List(Client("Bob", 20), Client("Cindy", 30))
}
I want Client.clients to be determined at runtime, with the flexibility of either reading it from a properties file or from a database. In the Java world I'd define an interface, implement the two types of source, and use DI to assign a class variable:
trait ConfigSource {
def clients : List[Client]
}
object ConfigFileSource extends ConfigSource {
override def clients = buildClientsFromProperties(Properties("clients.properties"))
//...etc, read properties files
}
object DatabaseSource extends ConfigSource { /* etc */ }
object Client {
#Resource("configuration_source")
private var config : ConfigSource = _ //Inject it at runtime
val clients = config.clients
}
This seems like a pretty clean solution to me (not a lot of code, clear intent), but that var does jump out (OTOH, it doesn't seem to me really troublesome, since I know it will be injected once-and-only-once).
What would the Reader monad look like in this situation and, explain it to me like I'm 5, what are its advantages?
Let's start with a simple, superficial difference between your approach and the Reader approach, which is that you no longer need to hang onto config anywhere at all. Let's say you define the following vaguely clever type synonym:
type Configured[A] = ConfigSource => A
Now, if I ever need a ConfigSource for some function, say a function that gets the n'th client in the list, I can declare that function as "configured":
def nthClient(n: Int): Configured[Client] = {
config => config.clients(n)
}
So we're essentially pulling a config out of thin air, any time we need one! Smells like dependency injection, right? Now let's say we want the ages of the first, second and third clients in the list (assuming they exist):
def ages: Configured[(Int, Int, Int)] =
for {
a0 <- nthClient(0)
a1 <- nthClient(1)
a2 <- nthClient(2)
} yield (a0.age, a1.age, a2.age)
For this, of course, you need some appropriate definition of map and flatMap. I won't get into that here, but will simply say that Scalaz (or RĂșnar's awesome NEScala talk, or Tony's which you've seen already) gives you all you need.
The important point here is that the ConfigSource dependency and its so-called injection are mostly hidden. The only "hint" that we can see here is that ages is of type Configured[(Int, Int, Int)] rather than simply (Int, Int, Int). We didn't need to explicitly reference config anywhere.
As an aside, this is the way I almost always like to think about monads: they hide their effect so it's not polluting the flow of your code, while explicitly declaring the effect in the type signature. In other words, you needn't repeat yourself too much: you say "hey, this function deals with effect X" in the function's return type, and don't mess with it any further.
In this example, of course the effect is to read from some fixed environment. Another monadic effect you might be familiar with include error-handling: we can say that Option hides error-handling logic while making the possibility of errors explicit in your method's type. Or, sort of the opposite of reading, the Writer monad hides the thing we're writing to while making its presence explicit in the type system.
Now finally, just as we normally need to bootstrap a DI framework (somewhere outside our usual flow of control, such as in an XML file), we also need to bootstrap this curious monad. Surely we'll have some logical entry point to our code, such as:
def run: Configured[Unit] = // ...
It ends up being pretty simple: since Configured[A] is just a type synonym for the function ConfigSource => A, we can just apply the function to its "environment":
run(ConfigFileSource)
// or
run(DatabaseSource)
Ta-da! So, contrasting with the traditional Java-style DI approach, we don't have any "magic" occurring here. The only magic, as it were, is encapsulated in the definition of our Configured type and the way it behaves as a monad. Most importantly, the type system keeps us honest about which "realm" dependency injection is occurring in: anything with type Configured[...] is in the DI world, and anything without it is not. We simply don't get this in old-school DI, where everything is potentially managed by the magic, so you don't really know which portions of your code are safe to reuse outside of a DI framework (for example, within your unit tests, or in some other project entirely).
update: I wrote up a blog post which explains Reader in greater detail.

Correct usage of mutable/immutable lists

At the moment, Im trying to understand Functional Programming in Scala and I came across a problem I cannot figure out myself.
Imagine the following situation:
You have two classes: Controller and Bot. A Bot is an independent Actor which is initiated by a Controller, does some expensive operation and returns the result to the Controller. The purpose of the Controller is therefore easy to describe: Instantiate multiple objects of Bot, start them and receive the result.
So far, so good; I can implement all this without using any mutable objects.
But what do I do, if I have to store the result that a Bot returns, to use it later as input for another Bot (and later on means that I don't know when at compile time!)?
Doing this with a mutable list or collection is fairly easy, but I add a lot of problems to my code (as we are dealing with concurrency here).
Is it possible, following the FP paradigm, to solve this by using immutable objects (lists...) safely?
BTW, im new to FP, so this question might sound stupid, but I cannot figure out how to solve this :)
Actors usually have internal state, being, themselves, mutable beasts. Note that actors are not a FP thing.
The setup you describe seems to rely on a mutable controller, and it is difficult to get around it in a language that is not non-strict by default. Depending on what you are doing, though, you could rely on futures. For example:
case Msg(info) =>
val v1 = new Bot !! Fn1(info)
val v2 = new Bot !! Fn2(info)
val v3 = new Bot !! Fn3(info)
val v4 = new Bot !! Fn4(v1(), v2(), v3())
reply(v4())
In this case -- because !! returns a Future -- v1, v2 and v3 will be computed in parallel. The message Fn4 is receiving as parameters the futures applied, meaning it will wait until all values are computed before it starts computing.
Likewise, the reply will only be sent after v4 has been computed, as the future has been applied for as well.
A really functional way of doing these things is the functional reactive programming, or FRP for short. It is a different model than actors.
The beauty of Scala, though, is that you can combine such paradigms to the extent that better fits your problem.
This is how an Erlang-like actor could look in Scala:
case class Actor[State](val s: State)(body: State => Option[State]) { // immutable
#tailrec
def loop(s1: State) {
body(s1) match {
case Some(s2) => loop(s2)
case None => ()
}
}
def act = loop(s)
}
def Bot(controller: Actor) = Actor(controller) {
s =>
val res = // do the calculations
controller ! (this, res)
None // finish work
}
val Controller = Actor(Map[Bot, ResultType]()) {s =>
// start bots, perhaps using results already stored in s
if (
// time to stop, e.g. all bots already finished
)
None
else
receive {
case (bot, res) => Some(s + (bot -> res)) // a bot has reported result
}
}
Controller.act