Description
I have noticed the answer on #2042 and read the concerns expressed in #2065 which is presented as a solution to this problem.
While I concur with the naming challenges and the fact that we cannot use the name takeUntil
in Kotlin for this purpose, I do believe the use case of ensuring a flow is finite / completes is quite important and prevalent especially since the addition of StateFlow
and SharedFlow
, and is worth a dedicated operator.
transformWhile
indeed does the job, but it really doesn't convey the message cleanly, which after all is why I personally love Kotlin's collection and flow operators. takeWhile
, drop(n)
, etc. really read well, but transformWhile { emit(it); it.isNotTheLastOne() }
honestly doesn't. In particular it's unclear whether the element will be emitted if we return false (of course it is, since we emit before reaching the condition, but what I mean is that it's not obvious). The point is that the goal of this snippet doesn't pop right away at first glance. The code seems too complex to express a single idea - we're doing multiple things.
Since the use case at hand is about ensuring flow completion on a certain condition, I would like to suggest completeAfter { it.isTheLastOne() }
as a possible name for this function. The name would suggest that we make the flow "complete" when a given condition is met, while still suggesting the element matching the condition will be included.
I understand that it doesn't follow the take
convention, but it's actually not what we want to express here. The focus is not on the fact that all elements match a condition and we want to take them. The focus is about completing the flow after we see a particular sentinel value.
Another possible option would be dropAfter
, which would match other helpers like substringAfter
, and follow the drop
naming convention for cutting off the end of a flow or collection. It would be slightly more general-sounding than completeAfter
, but with less emphasis on the "completion" aspect - making the flow finite.
If such an operator is not included in the coroutines lib, I believe a lot of projects will add their own and we'll end up with no common name for this operation, which would be sad for the ecosystem IMO.