Skip to content

Instantly share code, notes, and snippets.

@pokk
Last active April 5, 2017 02:31
Show Gist options
  • Save pokk/d4946e5b8c8670e09bfae1cf49273437 to your computer and use it in GitHub Desktop.
Save pokk/d4946e5b8c8670e09bfae1cf49273437 to your computer and use it in GitHub Desktop.
delay search for searchTextView

Introduction

Search data from inputing text.

Talk is cheap. Show me the code.

I have two ways to archive it, as below.

  • RxKotlin
// Create a calling self rx operation.
val subject = PublishSubject<String>().apply {
    compose(bindToLifecycle<String>())
    debounce(500, TimeUnit.MICROSECONDS)  // Delay 500ms.
    subscribeOn(Schedulers.io())
    observeOn(AndroidSchedulers.mainThread())
    doOnNext {
        // Search local data or remote data.
    }
    subscribe()
}

// Using RxBinding for search text view.
RxTextView.textChanges(textview).subscribe {
    if (!it.isNullOrEmpty())
        // Omitting the data.
        subject.onNext(it.toString())
}
  • Handler + Thread
private handler: Handler = Handler()

private fun queryWithHandler(newText: String) {
    // Delay 500ms.
    if (delayQueryTask != null) {
        delayQueryTask.cancel()
        handler.removeCallbacksAndMessages(null)
    }
    delayQueryTask = DelayQueryRunnable(newText)
    handler.postDelayed(delayQueryTask, 500)
}

private inner class DelayQueryRunnable(internal var mText: String): Runnable {
    private var canceled = false

    override fun run() {
        if (canceled) {
            return
        }
        queryMatch(mText)
    }

    fun cancel() {
        canceled = true
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment