Skip to content

Instantly share code, notes, and snippets.

@handstandsam
Last active July 19, 2021 09:50
Show Gist options
  • Save handstandsam/1007031cea66e9862bed44840fafb92e to your computer and use it in GitHub Desktop.
Save handstandsam/1007031cea66e9862bed44840fafb92e to your computer and use it in GitHub Desktop.
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")
@Test
fun testMutableDataIsBad() = runBlockingTest {
val somePojo = SomePojo()
val mutableStateFlow = MutableStateFlow(somePojo)
println("INITIAL: ${mutableStateFlow.value}")
// Update the value
somePojo.name = "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)
@norrisboat
Copy link

Thanks very much for this

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