Reputation: 877
I have a list that for example has 101 record, i want to send data in batch of 10. list.grouped(10) will return 10 lists having 10 records and 1 list with one record. I want to send all ten lists with 10 records to futureSend method and want to get the list with one record(if exists in this scenario it does but if list has 100 records then return empty list) from this for comprehension. So if the list.size is not equals to ten, i do not want to send the list to futureSend and get that list from for comprehension.
val listRes = list.grouped(10)
for {
list <- listRes
if list.size == 10
_ = futureSend(list) map { result =>
println("sent")
)
}
} yield {}
I want to yield the list with the size less than 10(do not call futureCall method in that case) and if all the lists have size 10 yield empty list.
Upvotes: 0
Views: 50
Reputation: 51271
A for
comprehension is the wrong tool for the job.
val listRes = list.grouped(10).toList
listRes.init.foreach{group => futureSend(group); println("sent")}
val last = listRes.last
val remainder = if (last.length < 10) last
else {
futureSend(last)
println("sent")
List.empty[ElementType]
}
If you're on Scala 2.13.x then there's a slightly more efficient option.
val remainder = List.unfold(list.grouped(10)){ itr =>
Option.when(itr.hasNext) {
val thisBatch = itr.next()
if (itr.hasNext || thisBatch.size == 10) {
futureSend(thisBatch)
println("sent")
(List(), itr)
} else (thisBatch, itr)
}
}.flatten
Upvotes: 2