Skip to content

Instantly share code, notes, and snippets.

@jisungbin
Last active August 5, 2022 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jisungbin/b546b84a6afc8c25f3de34db72c96a1c to your computer and use it in GitHub Desktop.
Save jisungbin/b546b84a6afc8c25f3de34db72c96a1c to your computer and use it in GitHub Desktop.
open class PeopleWrapper(open val name: String, open val age: Int) {
override fun toString() = "name: $name, age: $age"
}
class MutablePeopleWrapper(name: String, age: Int) : PeopleWrapper(name, age) {
private val _name = MutableStateFlow(name)
override var name
get() = _name.value
set(value) {
_name.value = value
}
private val _age = MutableStateFlow(age)
override var age
get() = _age.value
set(value) {
_age.value = value
}
fun asStateFlow() = object : StateFlow<PeopleWrapper> {
override val replayCache get() = listOf(value)
override val value
get() = PeopleWrapper(
name = _name.value,
age = _age.value
)
override suspend fun collect(collector: FlowCollector<PeopleWrapper>): Nothing =
coroutineScope {
combine(_name, _age) { params ->
PeopleWrapper(
name = params[0] as String,
age = params[1] as Int
)
}.stateIn(this).collect(collector)
}
}
}
fun People(name: String, age: Int) = MutablePeopleWrapper(name, age)
class MainActivity : ComponentActivity() {
private val people = People("Ji", 0)
/**
* [Dispatchers.Main]
* I/System.out: name: Sungbin, age: 21
*
* [Dispatchers.Main.immediate]
* I/System.out: name: Ji, age: 0
* I/System.out: name: Sungbin, age: 0
* I/System.out: name: Sungbin, age: 21
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
CoroutineScope(Dispatchers.Main.immediate).launch {
people.asStateFlow().collect {
println(it)
}
}
}
override fun onResume() {
super.onResume()
people.apply {
name = "Sungbin"
age = 21
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment