Direct Use of Futures in Acca

I cannot create the Future as described here . It says that you can create Future directly using the following code:

 import akka.dispatch.Await import akka.dispatch.Future import akka.util.duration._ val future = Future { "Hello" + "World" } val result = Await.result(future, 1 second) 

Using the same code, I get the error message: error: could not find implicit value for parameter executor: akka.dispatch.ExecutionContext . All I can find about ExecutionContext is what you can β€œdo with it”. In the documentation, the only line I found was:

 implicit val ec = ExecutionContect.fromExecutionService(yourExecutionServiceGoesHere) 

But that did not help me. Anyone have any suggestions on this topic? How can I create a new Future without an Actor request?

+2
source share
2 answers

If you have an ActorSystem , then it will have an ExecutionContext , which can be used here. It must be implicit unless you pass it explicitly to the Future.apply method.

To demonstrate, if you just want to see how this works in REPL:

 implicit val system = ActorSystem("MySystem").dispatcher 

(There is also an implicit conversion ActorSystem => ExecutionContext object.)

To create modular code without creating a context immediately before the point of use, consider making the context an abstract element of the attribute:

 trait MyFutures { implicit val context: ExecutionContext def helloFuture: Future[String] = Future { "hello" + "world" } } 
+7
source

Your code does not compile because you are writing illegal Scala code: the signature Future.apply clearly states this. I assume that you understand that you are calling the apply method of the companion object for the Future property, which looks like this:

 object Future extends java.lang.Object with scala.ScalaObject { def apply[T](body : => T)(implicit executor : akka.dispatch.ExecutionContext) : akka.dispatch.Future[T] = { /* compiled code */ } } 

Since you do not have the implicit ExecutionContext available when calling Future.apply , you get a compilation error. This is the same as calling a method that takes two parameters if you provide only one.

The problem of creating an ExecutionContext is different, and you can find the answer in the Akka documentation:

To perform callbacks and operations, Futures needs something called ExecutionContext, which is very similar to java.util.concurrent.Executor. if you have an ActorSystem, it will use the default dispatcher as ExecutionContext, or you can use the factory methods provided by the ExecutionContext companion object to wrap Executors and ExecutorServices, or even create one yourself.

+3
source

Source: https://habr.com/ru/post/980981/


All Articles