Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
package com.handstandsam.mutablestateflow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Test
class UseImmutableDataWithMutableStateFlow {
data class SomePojo(var name: String = "placeholder")
fun testMutableDataIsBad() = runBlockingTest {
val somePojo = SomePojo()
val mutableStateFlow = MutableStateFlow(somePojo)
println("INITIAL: ${mutableStateFlow.value}")
// Update the value = "Something Different"
// Assign the new value to the MutableStateFlow
println("CURRENT: ${mutableStateFlow.value}")
mutableStateFlow.value = somePojo
println("UPDATED: ${mutableStateFlow.value}")
// It's the same object you already modified and therefore the value is the same,
// and no emission will occur from the MutableStateFlow
INITIAL: SomePojo(name=placeholder)
CURRENT: SomePojo(name=Something Different)
UPDATED: SomePojo(name=Something Different)
Copy link

norrisboat commented May 28, 2021

Thanks very much for this

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