Kotlin Android debounce

前端 未结 10 831
佛祖请我去吃肉
佛祖请我去吃肉 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:14

    Thanks to https://medium.com/@pro100svitlo/edittext-debounce-with-kotlin-coroutines-fd134d54f4e9 and https://stackoverflow.com/a/50007453/2914140 I wrote this code:

    private var textChangedJob: Job? = null
    private lateinit var textListener: TextWatcher
    
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
    
        textListener = object : TextWatcher {
            private var searchFor = "" // Or view.editText.text.toString()
    
            override fun afterTextChanged(s: Editable?) {}
    
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
    
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                val searchText = s.toString().trim()
                if (searchText != searchFor) {
                    searchFor = searchText
    
                    textChangedJob?.cancel()
                    textChangedJob = launch(Dispatchers.Main) {
                        delay(500L)
                        if (searchText == searchFor) {
                            loadList(searchText)
                        }
                    }
                }
            }
        }
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    
        editText.setText("")
        loadList("")
    }
    
    
    override fun onResume() {
        super.onResume()
        editText.addTextChangedListener(textListener)
    }
    
    override fun onPause() {
        editText.removeTextChangedListener(textListener)
        super.onPause()
    }
    
    
    override fun onDestroy() {
        textChangedJob?.cancel()
        super.onDestroy()
    }
    

    I didn't include coroutineContext here, so it probably won't work, if not set. For information see Migrate to Kotlin coroutines in Android with Kotlin 1.3.

提交回复
热议问题