Skip to content

Instantly share code, notes, and snippets.

@sys1yagi
Last active May 17, 2019 01:19
Show Gist options
  • Save sys1yagi/5269fe310573f7ef766bdf984882d954 to your computer and use it in GitHub Desktop.
Save sys1yagi/5269fe310573f7ef766bdf984882d954 to your computer and use it in GitHub Desktop.
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