Last active
March 12, 2021 00:21
-
-
Save truedem/03923ea0521d693c30ed3934af6c98bd to your computer and use it in GitHub Desktop.
Extention function tu turn EditText input on Android into StateFlow
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
// source: https://github.com/HamdiBoumaiza/Stars/blob/main/app/src/main/java/com/hb/stars/utils/Extensions.kt | |
// extention function anywhere: | |
fun EditText.getTextChangeStateFlow(): StateFlow<String> { | |
val query = MutableStateFlow("") | |
addTextChangedListener { | |
query.value = it.toString() | |
} | |
return query | |
} | |
// https://github.com/HamdiBoumaiza/Stars/blob/main/app/src/main/java/com/hb/stars/ui/search/SearchCharactersActivity.kt | |
// in activity or fragment | |
@FlowPreview | |
@ExperimentalCoroutinesApi | |
@SuppressLint("ClickableViewAccessibility") | |
private fun setEditTextListener() { | |
lifecycleScope.launch { | |
binding.mySearchField.getTextChangeStateFlow() | |
.debounce(200) | |
.filter { query -> | |
if (query.isEmpty()) { | |
runOnUiThread { setError(null) } | |
return@filter false | |
} else { | |
return@filter true | |
} | |
} | |
.distinctUntilChanged() | |
.flatMapLatest { query -> | |
viewModel.searchCharacters(query) | |
} | |
.flowOn(Dispatchers.Default) | |
.collect { result -> | |
processResult(result) | |
} | |
} | |
} | |
fun processResult(result: MyResult) { } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment