【问题标题】:Android EditText Coroutine debounce operator like RxJavaAndroid EditText 协程去抖操作符,如 RxJava
【发布时间】:2020-12-05 04:08:37
【问题描述】:

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

想知道在这种情况下是否有解决方案可以在不使用延迟的情况下使用协程使 EditText 去抖动。

【问题讨论】:

  • 我在这里回答了一个关于按钮的类似问题,我的评论也是一样的。为此,协程是不必要的复杂性。 stackoverflow.com/a/60193549/506796
  • 你可能是对的,但这是我学习协程的方式,所以我不得不尝试一下。

标签: android kotlin kotlin-coroutines coroutine


【解决方案1】:

将文本更改事件转为Flow

使用 kotlinx.coroutines 1.5.0

@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) {
        trySend(s)
      }
    }
    addTextChangedListener(listener)
    awaitClose { removeTextChangedListener(listener) }
  }.onStart { emit(text) }
}

如果使用androidx.core.widget.doOnTextChanged

@ExperimentalCoroutinesApi
@CheckResult
fun EditText.textChanges(): Flow<CharSequence?> {
  return callbackFlow {
    checkMainThread()

    val listener = doOnTextChanged { text, _, _, _ -> trySend(text) }
    awaitClose { removeTextChangedListener(listener) }
  }.onStart { emit(text) }
}

用途:

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

还有这样的:

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

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

源码:https://github.com/Kotlin-Android-Open-Source/MVI-Coroutines-Flow/blob/master/core-ui/src/main/java/com/hoc/flowmvi/core_ui/FlowBinding.kt#L116

【讨论】:

【解决方案2】:

在对 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 1970-01-01
    相关资源
    最近更新 更多