Conditional Display
Handling no results
When a search returns no results, you might want to display specific content bringing the user back to a successful search. To do this, subscribe to the Searcher
’s response
and show your no-results UI when the response has no hits
:
Example
1
2
3
4
5
6
7
searcher.response.subscribe {
if (it == null || it.hitsOrNull.isNullOrEmpty()) {
showNoResultsUI()
} else {
hideNoResultsUI()
}
}
Handling errors
When an error occurs you might want to display some specific content helping the user go back to a search that was successful.
To be notified of errors, subscribe to the Searcher
’s error
field:
1
2
3
4
5
searcher.error.subscribe {
if (it != null) {
Log.e("TAG", "Error on search $query: ${it.message}")
}
}
Handling empty query
By default, InstantSearch Android will always display results, even when the query is empty. In some cases you may want to hide the results on the empty query.
To override this default behavior, you can implement your own SearchBoxView
. Instead of calling onQueryChanged
(for search-as-you-type) or onQuerySubmitted
with every query you want to execute, you only call them when the query is not empty:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class SearchBoxNoEmptyQuery(
public val searchView: SearchView
) : SearchBoxView {
override var onQueryChanged: Callback<String?>? = null
override var onQuerySubmitted: Callback<String?>? = null
init {
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
query?.isNotEmpty()?.let { onQuerySubmitted?.invoke(query) }
return false
}
override fun onQueryTextChange(query: String?): Boolean {
query?.isNotEmpty()?.let { onQuerySubmitted?.invoke(query) }
return false
}
})
}
override fun setText(text: String?) {
searchView.setQuery(text, false)
}
}