1

I am currenctly stuck, the answer is probably somewhere on google but I don't know what word to use this time so I hope someone can help me here.

I have a list of element and I want to apply a fuction to each element but I want to wait between each elements.

I have something like that for now :

  val numbers = List(10, 11, 12,13,14)
  numbers.foreach(i => {
    //do some stuff with i
    Thread.sleep(1000)
  })

but I don't think it's proper way to do it. Maybe there is a way that do not block everything?

Kimiaoi
  • 11
  • 2
  • 1
    Why do you want to await between each element? If this function is doing something heavy like calling an externals service or something like that, then it would be good to use a more appropriate concurrent abstraction, for example streams _(`fs2`, `AkkaStream`, `Monix Observables`, `ZIO ZStreams`)_ – Luis Miguel Mejía Suárez Aug 21 '20 at 13:26

1 Answers1

1

In plain Scala on JVM you can use Java's ScheduledExecutorService:

val list: List[Int] = List(1,2,3)

private val es: ScheduledExecutorService = Executors.newScheduledThreadPool(1)

type ResultType = Unit

val futures: Seq[ScheduledFuture[ResultType]] = list.zipWithIndex.map { case (integer, index) =>
  val runnable: Callable[ResultType] = () => println(integer)
  es.schedule(runnable, index*1, duration.SECONDS)
}

Actually there is a topic about scheduled Scala Future - Scala - ScheduledFuture

With help of this approach you can write the same logic that I introduced above:

val list: List[Int] = List(1,2,3)

type ResultType = Unit

val futures: Seq[Future[ResultType]] = list.zipWithIndex.map { case (integer, index) =>
  DelayedFuture(index * 1.seconds)(println(integer))
}
Artem Sokolov
  • 810
  • 4
  • 8