像RxJava这样的Android EditText Coroutine防反跳运算符 [英] Android EditText Coroutine debounce operator like RxJava

查看:82
本文介绍了像RxJava这样的Android EditText Coroutine防反跳运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使EditText具有自动建议功能,并且需要听其输入.以编程方式设置EditText时,我还需要忽略它.

I need to make EditText with autosuggest functionality and I need to listen to its input. I also need to ignore EditText change when it is set programmatically.

想知道是否有解决方案可以在不使用延迟的情况下使用协同程序来对EditText进行去抖动.

Wondering if there is solution to make debounce EditText with Coroutines without using delay in this situation.

推荐答案

将文本更改事件转换为 Flow

Turn text change event to a Flow

@ExperimentalCoroutinesApi
@CheckResult
fun EditText.textChanges(): Flow<CharSequence?> {
  return callbackFlow<CharSequence?> {
    val listener = object : TextWatcher {
      override fun afterTextChanged(s: Editable?) = Unit
      override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
      override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        offer(s)
      }
    }
    addTextChangedListener(listener)
    awaitClose { removeTextChangedListener(listener) }
  }.onStart { emit(text) }
}

并使用:

editText.textChanges().debounce(300)
    .onEach { ... }
    .launchIn(lifecycleScope)

是这样的:

fun executeSearch(term: String): Flow<SearchResult> { ... }

editText.textChanges()
    .distinctUntilChanged()
    .filterNot { it.isNullOrBlank() } 
    .debounce(300)
    .flatMapLatest { executeSearch(it) }
    .onEach { updateUI(it) }
    .launchIn(lifecycleScope)

这篇关于像RxJava这样的Android EditText Coroutine防反跳运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆