Last active
May 17, 2019 01:19
-
-
Save sys1yagi/5269fe310573f7ef766bdf984882d954 to your computer and use it in GitHub Desktop.
Observation of state change of View by Flow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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" | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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