Kotlin / kotlinx.coroutines

Library support for Kotlin coroutines
Apache License 2.0
13.05k stars 1.85k forks source link

Provide some kind of compile time warning when using Mutable*Flows with mutable collections #2516

Open zach-klippenstein opened 3 years ago

zach-klippenstein commented 3 years ago

A question that comes up fairly regularly on the slack is, "why doesn't my MutableStateFlow emit when I add an item to a MutableList?" The solution is almost always to use an immutable list instead.

While there might be valid reasons for emitting mutable lists in flows, i think they are probably rare and definitely seem to make a sharp edge for new developers.

It would be great to have a lint check to warn about this, but since kotlin doesn't have a standard linter, maybe an overload of the constructor functions that is hidden/deprioritized from auto-complete, takes mutable collection types, and is annotated with some sort of warning-causing annotation (maybe a custom OptIn?) could be introduced?

Probably a similar check could be useful for emit, send, etc, although I think Mutable*Flow is the most common path through which this mistake gets made.

gildor commented 3 years ago

but since kotlin doesn't have a standard linter

It can be a part of Kotlin IDE Plugin, though it will not emit compiler warning, but many similar cases already covered by Kotlin IDE integration (I'm not against library-level solution, just want to point out that IDE solution is also pretty common)

zach-klippenstein commented 3 years ago

Yea, I'd be happy with IDE-only too.