Skip to content

Instantly share code, notes, and snippets.

@pbhoraskar911
Created April 27, 2020 06:21
Show Gist options
  • Select an option

  • Save pbhoraskar911/51e073e1cf7eec4644af2b275038b76c to your computer and use it in GitHub Desktop.

Select an option

Save pbhoraskar911/51e073e1cf7eec4644af2b275038b76c to your computer and use it in GitHub Desktop.
SearchActivityViewModel
var searchResponseLiveData : MutableLiveData<SearchResponse> = MutableLiveData()
var searchProgressBarLiveData : MutableLiveData<Boolean> = MutableLiveData()
/**
* Method to observe the text changes and filter out the appropriate stream to make the api call.
*/
fun processSearchTextChanges(changedText: InitialValueObservable<CharSequence>) {
compositeDisposable.add(
changedText
.skipInitialValue()
.debounce(500, TimeUnit.MILLISECONDS)
.doOnNext {
if (it.trim().toString().length >= 3)
searchProgressBarLiveData.postValue(true)
}
.filter {
it.trim().toString().length >= 3
}
.flatMapSingle {
fetchSearchResults(it.trim().toString())
}
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({
// success
searchProgressBarLiveData.postValue(false)
searchResponseLiveData.postValue(it)
}, {
// error
searchProgressBarLiveData.postValue(false)
searchResponseLiveData.postValue(Resource.error())
})
)
}
/**
* Method to make the Auto Suggestion Search Api call.
*/
private fun fetchSearchResults(searchTerm: String?): Single<SearchResponse> {
return searchRepository.getAutoSuggestionResults(searchTerm!!)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment