Is there a better alternative abstraction alternative to represent long running, asynchronous task?

A Futureis good for presenting one asynchronous task that will / should be completed within a certain fixed period of time.

However, there is another kind of asynchronous task where it is impossible / very difficult to know exactly when it will end. For example, the time spent on a particular line-processing task may depend on various factors, such as the size of the input.

For this kind of task, failure detection can be better if you check if the task can make progress within a reasonable amount of time, instead of setting a hard timeout value, for example, to Future.

Are there libraries providing a suitable monadic abstraction of this kind of task in Scala?

+4
source share
3 answers

You can use a stream of values, for example:

sealed trait Update[T]
case class Progress[T](value: Double) extends Update[T]
case class Finished[T](result: T) extends Update[T]

let your task highlight Progress values ​​when it’s convenient (for example, every time a piece of calculation is completed) and emit one ready-made value after the complete calculation is complete. The consumer could check the meaning of progress to ensure that the task is still moving forward. If the consumer is not interested in updating the progress, you can simply filter it. I think this is more complex than acting.

, , akka streams scalaz. Akka DSL , . Scalaz , , .

+2

. Future - - . , .

1 - ( ):

val chunk1 = Future { ... } // chunk 1 starts execution here
val chunk2 = Future { ... } // chunk 2 starts execution here
val result = for {
  c1 <- chunk1
  c2 <- chunk2
} yield combine(c1, c2)

2 - :

val chunk1 = Future { ... } // chunk 1 starts execution here
val result = for {
  c1 <- chunk1
  c2 <- Future { c1 => ... } // chunk 2 starts execution here
} yield combine(c1, c2)

, , , , , sequence.

0

" Scala : " Scambler :

  • scala.concurrent.Future scala.util.Try, Try , , .
  • - scala.concurrent.Future, ExecutionContext. , .

, Future, Monad, Monad:

trait Monad[F[_]] {
  def flatMap[A,B](fa: F[A], f: A => F[B]): F[B]
  def pure[A](a: A): F[A]
}

// read the type parameter as "for all F, constrained by Monad".
final def load[F[_]: Monad](pageUrl: URL): F[Page]
0

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


All Articles