https://kotlinlang.org logo
Title
w

william

10/20/2020, 11:53 PM
looking for a flow operator that does something like input: Foo output: List<Foo> everytime the upstream flow emits, the operator would emit a list of this value and any previous values that are emitted
m

Marc Knaup

10/21/2020, 1:32 AM
.scan(emptyList<Foo>()) { list, element -> list + element }
☝️ 2
w

william

10/21/2020, 12:29 PM
ty 🙂
e

ephemient

10/21/2020, 1:37 PM
FYI ^^ is O(N²)
this is O(N), if it matters to you (but it may not)
👍 1
m

Marc Knaup

10/21/2020, 1:50 PM
If performance is critical I would definitely run benchmarks. It’s a good idea to use a shared list where the elements already emitted are never replaced. I’d use a
MutableList
instead of array though and let the stdlib handle the expansion.
ArrayList
implementation is incredibly fast.
e

ephemient

10/21/2020, 1:52 PM
the problem is that you need something like
.subList()
to avoid copying
otherwise all earlier flow emissions are invalidated when you mutate the list, which I believe breaks expectations
but extending mutable list will cause any earlier
.subList()
values to break with ConcurrentModificationException
hence the manual array extending and list wrapping
m

Marc Knaup

10/21/2020, 1:53 PM
Ah, you’re right