I’m behind the times (circa Kotlin 1.3), and would like to use the latest flow functions to do this the most “clean” way.
- I have a flow of messages
- Those messages update a state of the current “span”
- Sometimes those messages indicate the end of the current span, time to emit a completed “unit” of work.
Is this a MutableStateFlow
?
I made up a toy case of listening to the radio to demonstrate the question:
commandLineToFlow(command = "listen to the radio") // works!
.dropExtraNoise() // Commercials, so many commercials.
.logToKnownUpdates() // classify and formalize!
.distinctUntilChanged() // avoid repeats
.onEach { println("-- A message we should act on: $it") }
.transform<Message, Song> { message->
// New song started, emit old song
// this part feels... kludgy.
if((message.type ==Type.TITLE && message.value != currentSong.title) ||
(message.type == Type.ARTIST && message.value != currentSong.artist)) {
emit(currentSong.copy())
}
// Do updates. *** This feels wrong, like a running state....
when(message.type) {
// stuff that warrants a full new song
Type.ARTIST->currentSong = Song(
artist = message.value,
title = currentSong.title,
)
Type.TITLE->currentSong = Song(
artist=currentSong.artist,
title=message.value,
)
// stuff that DOESN'T warrant a full new song
Type.FILE->currentSong.files.add(message.value)
}
// stuff we should always do
currentSong.length = Duration.between(currentSong.start, Instant.now())
}