Mohamed Ibrahim
03/02/2020, 3:52 PMFlow<Product>
which emits one by one, how I make it to collect those in list so I could receive a list in collect()
louiscad
03/02/2020, 3:55 PMscan
.Mohamed Ibrahim
03/02/2020, 4:04 PMfun <T> Flow<T>.intoList(): Flow<List<T>> {
return flow {
val bag = arrayListOf<T>()
collect {
bag.add(it)
}
emit(bag)
}
}
streetsofboston
03/02/2020, 4:11 PMMohamed Ibrahim
03/02/2020, 4:14 PMstreetsofboston
03/02/2020, 4:18 PMcollect
will suspend forever. It will keep adding items to bag
, but emit(bag)
will never be called in that casecollect
on it, and your collect
call suspends.
• The lambda provided to your collect
call will be called each time your source/producer Flow calls emit
.
• In the mean time your call to collect
remains suspended.
• Your call to collect
resumes when the lambda provided to your source/producer Flow returns/*ends*.louiscad
03/02/2020, 4:37 PMemit
after each call to add
inside the collect
lambda.streetsofboston
03/02/2020, 4:45 PMscan
operator, emitting a growing list each time. I think he was more thinking about a final terminating (and suspending) toList()
method on the source Flow…. but I could be wrong…louiscad
03/02/2020, 6:08 PMstreetsofboston
03/02/2020, 6:12 PMMohamed Ibrahim
03/02/2020, 7:59 PMval toList =
flowOf(1, 2,3).scan(emptyList<Int>()) { acc, value -> acc + value }.toList()
streetsofboston
03/02/2020, 10:44 PMscan
is a great way to do so.
But if you just need get one final list of all emissions (without any intermediate ones), toList()
is your friend, but that requires the flow to end (since a list can only contain a finite amount of items).