I have a list of Futures and I want to get the first one completed with a certain condition. Here is an example of a possible code:
val futureList: Future[List[T]] = l map (c => c.functionWithFuture())
val data = for {
c <- futureList
}yield c
data onSuccess {
case x => (x filter (d=> d.condition)).head
}
But it's not efficient, because I'll take only one element of the list, but computed all of them with a lot of latency.
I know firstCompletedOf
but it's not what I'm searching.
(Sorry for my bad English.)
Try using a
Promise
and callingtrySuccess
on it as soon as a future that satisfies the condition completes. The first to calltrySuccess
will complete the future, the following ones will have no effect (as opposed to callingsuccess
, which can only be called once on aPromise
).Keep in mind that if no future in the list satisfies the condition, you will never have a result, i.e. the promise future will never complete.