Let's say I am having a future defined like shown below:
import scala.concurrent.Future
def appendCharWithTimeout(transformationId: String, char: Char, delayTimeMs: Long, delayTimes: Int) = (s: String) => {
for (i <- 1 to delayTimes) {
println(s"$transformationId waiting iteration $i ...")
Thread.sleep(delayTimeMs)
}
s"$s$char"
}
Future("Hello ")
.map( appendCharWithTimeout("mapJ", 'J', 200, 5) )
.map( appendCharWithTimeout("mapO", 'o', 200, 5) )
.map( appendCharWithTimeout("mapH", 'h', 200, 5) )
.map( appendCharWithTimeout("mapN", 'n', 200, 5) )
.map( appendCharWithTimeout("map!", '!', 200, 5) )
The execution time of this future is 5 seconds (5 * 5 * 200ms).
I am looking for a way to wrap this future in some sort of "timeout context" and stop the execution by timeout thus not all the transformations will be executed.
Ideally, I envision to have something like this:
Future("Hello ")
.within(2 seconds)
.map( appendCharWithTimeout("mapJ", 'J', 200, 5) )
.map( appendCharWithTimeout("mapO", 'o', 200, 5) )
.map( appendCharWithTimeout("mapH", 'h', 200, 5) )
.map( appendCharWithTimeout("mapN", 'n', 200, 5) )
.map( appendCharWithTimeout("map!", '!', 200, 5) )
And the output should be:
mapJ waiting iteration 1 ...
mapJ waiting iteration 2 ...
mapJ waiting iteration 3 ...
mapJ waiting iteration 4 ...
mapJ waiting iteration 5 ...
mapO waiting iteration 1 ...
mapO waiting iteration 2 ...
mapO waiting iteration 3 ...
mapO waiting iteration 4 ...
mapO waiting iteration 5 ...