Skip to content

Instantly share code, notes, and snippets.

@sys1yagi
Last active May 17, 2019
Embed
What would you like to do?
Observation of state change of View by Flow
// in Activity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleScope.launchWhenCreated {
editNickName.textChangeAsFlow()
.map { it?.isNotEmpty() ?: false }
.collect {
sendButton.isEnabled = it
}
}
// if you want to get 1 hot stream and n cold stream,
// you can use broadcastIn()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleScope.launchWhenCreated {
val textChange = editNickName.textChangeAsFlow().broadcastIn(this).asFlow()
launch {
textChange
.map { it?.isNotEmpty() ?: false }
.collect {
sendButton.isEnabled = it
}
}
launch {
textChange
.map { 140 - (it?.length ?: 0) }
.collect { remain ->
editNickNameLimit.text = "remain: $remain"
}
}
}
}
fun TextView.textChangeAsFlow() =
flowViaChannel<String?> { channel ->
channel.offer(text.toString())
val textWatcher = addTextChangedListener {
channel.offer(it?.toString())
}
channel.invokeOnClose {
removeTextChangedListener(textWatcher)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment