在对 Coroutines 和 Flow 进行了一些研究之后,我想出了创建自定义 EditText 的解决方案,它在其中包含去抖逻辑,使我能够附加去抖 TextWatcher 并在需要时将其删除。这是我的解决方案的代码
class DebounceEditText @JvmOverloads constructor(
context: Context,
attributeSet: AttributeSet? = null,
defStyleAttr: Int = 0
) : AppCompatEditText(context, attributeSet, defStyleAttr) {
private val debouncePeriod = 600L
private var searchJob: Job? = null
@FlowPreview
@ExperimentalCoroutinesApi
fun setOnDebounceTextWatcher(lifecycle: Lifecycle, onDebounceAction: (String) -> Unit) {
searchJob?.cancel()
searchJob = onDebounceTextChanged()
.debounce(debouncePeriod)
.onEach { onDebounceAction(it) }
.launchIn(lifecycle.coroutineScope)
}
fun removeOnDebounceTextWatcher() {
searchJob?.cancel()
}
@ExperimentalCoroutinesApi
private fun onDebounceTextChanged(): Flow<String> = channelFlow {
val textWatcher = object : TextWatcher {
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
override fun afterTextChanged(p0: Editable?) {
offer(p0.toString())
}
}
addTextChangedListener(textWatcher)
awaitClose {
removeTextChangedListener(textWatcher)
}
}
}
当我想激活 Debounce TextWatcher 时,我只需调用
// lifecycle is passed from Activity/Fragment lifecycle, because we want to relate Coroutine lifecycle with the one DebounceEditText belongs
debounceEditText.setOnDebounceTextWatcher(lifecycle) { input ->
Log.d("DebounceEditText", input)
}
在 xml 中实现 DebounceEditText 时出现焦点问题,因此我必须将可点击、可选择和 focusableInTouchMode 设置为 true。
android:focusable="true"
android:focusableInTouchMode="true"
android:clickable="true"
如果我想在 DebounceEditText 中设置输入而不触发,只需通过调用删除 TextWatcher
debounceEditText.removeOnDebounceTextWatcher()