Skip to content

Instantly share code, notes, and snippets.

@volo-droid
Last active April 4, 2025 10:14
Show Gist options
  • Save volo-droid/27479fb1d53c757a7bb6ce951a397e0e to your computer and use it in GitHub Desktop.
Save volo-droid/27479fb1d53c757a7bb6ce951a397e0e to your computer and use it in GitHub Desktop.
An experimental implementation of the flatMapLatest operator for StateFlow
/*
* Copyright (c) 2025 Volodymyr Galandzij
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
fun <T, R> StateFlow<T>.flatMapLatest(@BuilderInference transform: (value: T) -> StateFlow<R>): StateFlow<R> =
FlatMappedStateFlow(this, transform)
class FlatMappedStateFlow<T, R>(
private val upstream: StateFlow<T>,
private val mapper: (T) -> StateFlow<R>
) : StateFlow<R> {
override val replayCache: List<R>
get() = listOf(value)
override val value: R
get() = mapper(upstream.value).value
override suspend fun collect(collector: FlowCollector<R>): Nothing {
var previous: Any? = Unset
upstream
.map { mapper(it) }
.distinctUntilChanged()
.collectLatest { latestFlow ->
latestFlow.collect { value ->
if (value != previous) {
previous = value
collector.emit(value)
}
}
}
error("unreachable code")
}
private object Unset
}
@volo-droid
Copy link
Author

Inspired by the MappedStateFlow implementation:
Kotlin/kotlinx.coroutines#2514 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment