Set a limit to scala.rx timer - scala

Here is an example using Timer from scala.rx:
package tutorial.webapp
import akka.actor.ActorSystem
import rx.core.{Rx, Var}
import rx._
import rx.ops._
import scala.concurrent.Promise
import scala.concurrent.duration._
import scala.scalajs.js.JSApp
import scala.scalajs.js.annotation.JSExport
import scala.concurrent.ExecutionContext.Implicits.global
/**
* Created by IDEA on 29/10/15.
*/
object RxAddtionalOps extends JSApp {
#JSExport
override def main(): Unit = {
timer1
}
def timer1: Unit = {
implicit val scheduler = new DomScheduler
val t = Timer(100 millis)
var count = 0
val o = Obs(t){
count = count + 1
println(count)
}
}
}
When you run runMain tutorial.webapp.RxAddtionalOps from sbt, the console will be indefinitely blocked. Can I set a limit to the timer? For example, to make it stop emitting events in 2 minutes.

First of all, Scala is a language for express common programming patterns in a concise, elegant, and type-safe way. So keep your work tidy!
Therefore
import akka.actor.ActorSystem
import rx.core.{Rx, Var}
import rx._
import scala.concurrent.Promise
is a lot of unnecessary noise. And if the target is a JavaScript platform, the Actor system is not available yet, maybe over couple of years.
Why should you fire runMain tutorial.webapp.RxAddtionalOps in sbt, while a simple run command will do?
I used the Timer.kill() method to terminate the execution after a limited time:
package tutorial.webapp
import rx.Obs
import rx.ops.{DomScheduler, Timer}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.language.postfixOps
import scala.scalajs.js.JSApp
object RxAddtionalOps extends JSApp {
val executionStart = scala.compat.Platform.currentTime
def main(): Unit = {
timer1()
}
def timer1() = {
implicit val scheduler = new DomScheduler
val t = Timer(100 millis)
var count = 0
Obs(t) {
count += 1
println(count)
if (count >= 19) {
t.kill()
println(s"Successfully completed without errors. [within ${
scala.compat.Platform.currentTime - executionStart
} ms]")
}
}
}
}
Since it is actually a headless phantom or rhino environment (depending on your build.sbt config) there can be no user initiated interrupt processed.
For completeness here the build.sbt file:
name := "RxAddtionalOps"
version := "1.0"
scalaVersion := "2.11.7"
enablePlugins(ScalaJSPlugin)
scalacOptions ++= Seq("-unchecked", "-deprecation","-feature")
libraryDependencies ++= Seq(
"com.lihaoyi" %%% "scalarx" % "0.2.8",
"org.scala-js" %% "scalajs-library" % "0.6.5"
)

Related

methode map in class cats.data.Nested not recognized

I have a problem when folowing the scala cats library tutorial, the map method applied to the Nested class is highlighted with red, and the compiler doesn't recognize it.
here is my main class code :
import cats._
import cats.data._
import cats.implicits._
import cats.syntax.functor._
import cats.Functor
import cats.instances.list._
import cats.instances.option._
object Main extends App{
val list = List(Some(1), Some(2), None, Some(4))
val nested: Nested[List, Option, Int] = Nested(list)
//here is the problem
nested.map(_ + 1)
}
here is my build.sbt file
name := "dailySBT3"
version := "0.1"
scalaVersion := "2.12.5"
scalacOptions += "-Ypartial-unification"
libraryDependencies += "org.typelevel" %% "cats-core" % "1.1.0"
The problem is you are importing the instances and syntax twice. The following works for me with no problems:
import cats._
import cats.data._
import cats.implicits._
object Main extends App{
val list = List(Some(1), Some(2), None, Some(4))
val nested: Nested[List, Option, Int] = Nested(list)
nested.map(_ + 1)
}
You could also do the same thing as above but get rid of the cats.implicits._ import instead.
When in doubt, check out the cats import guide.

Exception while using Play WS to access a REST WebService

I want to use the Play WS Standalone (outside a Play Project) to call a simple Hello World RESTfull Web Service.
I'm Using an SBT Poject in Intelij IDEA whith this configuration :
name := "ScalaSbtProject"
version := "1.0"
scalaVersion := "2.11.7"
libraryDependencies += "com.typesafe.play" % "play-ws_2.11" % "2.5.10"
Here's my code :
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import play.api.libs.ws.ahc.AhcWSClient
import scala.util.{Failure, Success}
object Test {
def main(args: Array[String]): Unit = {
import scala.concurrent.ExecutionContext.Implicits._
implicit val actor = ActorSystem()
implicit val materializer = ActorMaterializer()
val wsClient = AhcWSClient()
val response = wsClient
.url("http://localhost:8080/WebService_war_exploded/service/test")
.get()
response.onComplete {
case Success(re) => { println(re.body)}
case Failure(e) => { e.getStackTrace.foreach(println)}
}
wsClient.close()
}
}
which throws this Exception :
Response Is Failed :
http://localhost:8080
org.asynchttpclient.netty.channel.NettyConnectListener.onFailure(NettyConnectListener.java:160)
org.asynchttpclient.netty.request.NettyChannelConnector$1.onFailure(NettyChannelConnector.java:103)
org.asynchttpclient.netty.SimpleChannelFutureListener.operationComplete(SimpleChannelFutureListener.java:28)
org.asynchttpclient.netty.SimpleChannelFutureListener.operationComplete(SimpleChannelFutureListener.java:20)
io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:514)
io.netty.util.concurrent.DefaultPromise.notifyListeners0(DefaultPromise.java:507)
io.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:486)
io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:427)
io.netty.util.concurrent.DefaultPromise.tryFailure(DefaultPromise.java:129)
io.netty.channel.nio.AbstractNioChannel.doClose(AbstractNioChannel.java:458)
io.netty.channel.socket.nio.NioSocketChannel.doClose(NioSocketChannel.java:235)
io.netty.channel.AbstractChannel$AbstractUnsafe.doClose0(AbstractChannel.java:632)
io.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:611)
io.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:554)
io.netty.channel.nio.NioEventLoop.closeAll(NioEventLoop.java:637)
io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:406)
io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:140)
io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)
java.lang.Thread.run(Thread.java:745)

Could not access type Unmarshaller in value akka.http.javadsl.unmarshalling

I am trying to write a simple Http client using Akka Http Client API. Towards this I have written the following code
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.unmarshalling._
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Sink, Source}
import scala.concurrent.duration._
import scala.concurrent.{Await}
import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import spray.json._
final case class Post(postId: Int, id: Int, name: String, email: String, body: String)
trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
implicit val postFormat = jsonFormat5(Post.apply)
}
class AkkaHttpClient extends App with Directives with JsonSupport {
implicit val system = ActorSystem("my-Actor")
implicit val actorMaterializer = ActorMaterializer()
implicit val executionContext = system.dispatcher
val httpClient = Http().outgoingConnection(host="http://jsonplaceholder.typicode.com/")
val flow = Source.single(HttpRequest(uri = Uri("/comments/1")))
.via(httpClient)
.mapAsync(1)(r => Unmarshal(r.entity).to[Post])
.runWith(Sink.head)
val results = Await.result(flow, 15 seconds)
println(results)
}
My build.sbt file looks like
name := "Akka-Http-Client"
version := "1.0"
scalaVersion := "2.11.8"
libraryDependencies ++= Seq(
"com.typesafe.akka" %% "akka-http-experimental" % "2.4.9-RC1",
"com.typesafe.akka" %% "akka-http-spray-json-experimental" % "2.4.9-RC1"
)
When I try to compile my code I get these errors
Error:scalac: missing or invalid dependency detected while loading class file 'Unmarshaller.class'.
Could not access type Unmarshaller in value akka.http.javadsl.unmarshalling,
because it (or its dependencies) are missing. Check your build definition for
missing or conflicting dependencies. (Re-run with `-Ylog-classpath` to see the problematic classpath.)
A full rebuild may help if 'Unmarshaller.class' was compiled against an incompatible version of akka.http.javadsl.unmarshalling.
I am having the same problem on 2.4.9-RC1, falling back to 2.4.8 solves the problem.
OR you could use this workaround described here: https://github.com/akka/akka/issues/21105

RxScala Observable never runs

With the following build.sbt:
name := "blah"
version := "1.0"
scalaVersion := "2.11.6"
libraryDependencies ++= Seq("io.reactivex" % "rxscala_2.11" % "0.24.1", "org.scalaj" %% "scalaj-http" % "1.1.4")
and this code:
import rx.lang.scala.Observable
import scala.concurrent.duration._
import scala.language.postfixOps
object Main {
def main(args: Array[String]): Unit = {
println("Ready?")
val o = Observable.interval(200 millis).take(5)
o.subscribe(n => println(s"n = ${n}"))
}
}
When I run it, all that's printed is Ready?; I see no n = ... at all.
I run using sbt run; it's built using Scala 2.6.11 and RxScala 0.24.1, as well as sbt 0.13. Any ideas?
The problem is that your program exits before o fires. Try the following code:
import rx.lang.scala.Observable
import scala.concurrent.duration._
import scala.language.postfixOps
object Main {
def main(args: Array[String]): Unit = {
println("Ready?")
val o = Observable.interval(200 millis).take(5)
o.subscribe(n => println(s"n = ${n}"))
Thread.sleep(5000)
}
}
Alternatively you can replace Thread.sleep with o.toBlocking.last, which cannot return before o terminates.

value resolveOne is not a member of akka.actor.ActorSelection

I get the above error message from here:
implicit val askTimeout = Timeout(60 seconds)
val workerFuture = workerContext actorSelection(payload.classname) resolveOne()
val worker = Await.result(workerFuture, 10 seconds)
worker ask Landau(List("1", "2", "3"))
specifically from the second line.. the import made is
import akka.actor._
import akka.util.Timeout
import akka.pattern.{ ask, pipe }
import scala.concurrent.duration._
import scala.concurrent.Await
import java.util.concurrent.TimeUnit
akka version is 2.2.1 and scala is 2.10.2, i'm using sbt 0.13 to build it all..
I cannot really understand what's wrong, since resolveOne is definetely coming from that package..
EDIT: I made a print of all the methods of the class with
ActorSelection.getClass.getMethods.map(_.getName).foreach { p => println(p)}
and this is the result:
apply
toScala
wait
wait
wait
equals
toString
hashCode
getClass
notify
notifyAll
I had the same problem and changed my Scala and Akka versions as described in the link below.
I brought here part of my build.sbt for simplicity:
scalaVersion := "2.10.4"
resolvers += "Akka Snapshot Repository" at "http://repo.akka.io/snapshots/"
libraryDependencies ++= Seq("com.typesafe.akka" %% "akka-actor" % "2.4-SNAPSHOT")
link: http://doc.akka.io/docs/akka/snapshot/intro/getting-started.html