Kotlin Android debounce

前端 未结 10 850
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 11:07

Is there any fancy way to implement debounce logic with Kotlin Android?

I\'m not using Rx in project.

There is a way in Java, but it is too big

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 11:12

    @masterwork,

    Great answer. This is my implementation for a dynamic searchbar with an EditText. This provides great performance improvements so the search query is not performed immediately on user text input.

        fun AppCompatEditText.textInputAsFlow() = callbackFlow {
            val watcher: TextWatcher = doOnTextChanged { textInput: CharSequence?, _, _, _ ->
                offer(textInput)
            }
            awaitClose { this@textInputAsFlow.removeTextChangedListener(watcher) }
        }
    
            searchEditText
                    .textInputAsFlow()
                    .map {
                        val searchBarIsEmpty: Boolean = it.isNullOrBlank()
                        searchIcon.isVisible = searchBarIsEmpty
                        clearTextIcon.isVisible = !searchBarIsEmpty
                        viewModel.isLoading.value = true
                        return@map it
                    }
                    .debounce(750) // delay to prevent searching immediately on every character input
                    .onEach {
                        viewModel.filterPodcastsAndEpisodes(it.toString())
                        viewModel.latestSearch.value = it.toString()
                        viewModel.activeSearch.value = !it.isNullOrBlank()
                        viewModel.isLoading.value = false
                    }
                    .launchIn(lifecycleScope)
        }
    

提交回复
热议问题