looking for a flow operator that does something li...
# coroutines
w
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
Copy code
.scan(emptyList<Foo>()) { list, element -> list + element }
☝️ 2
w
ty 🙂
e
FYI ^^ is O(N²)
this is O(N), if it matters to you (but it may not)
👍 1
m
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
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
Ah, you’re right