@@ -23,6 +23,7 @@ import com.algolia.search.helper.deserialize
23
23
import com.algolia.search.model.APIKey
24
24
import com.algolia.search.model.ApplicationID
25
25
import com.algolia.search.model.IndexName
26
+ import com.algolia.search.model.search.Query
26
27
import io.ktor.client.features.logging.*
27
28
28
29
class QuerySuggestionGuide : AppCompatActivity () {
@@ -38,6 +39,7 @@ class QuerySuggestionGuide : AppCompatActivity() {
38
39
)
39
40
private val suggestionSearcher = multiSearcher.addHitsSearcher(
40
41
indexName = IndexName (" instantsearch_query_suggestions" ),
42
+ query = Query (hitsPerPage = 3 )
41
43
)
42
44
private val searchBox = SearchBoxConnector (multiSearcher)
43
45
private val connection = ConnectionHandler (searchBox)
@@ -55,28 +57,27 @@ class QuerySuggestionGuide : AppCompatActivity() {
55
57
56
58
// Setup hits
57
59
val productAdapter = ProductAdapter ()
58
- binding.products.configureRecyclerView (productAdapter)
60
+ binding.products.configure (productAdapter)
59
61
connection + = productSearcher.connectHitsView(productAdapter) { it.hits.deserialize(Product .serializer()) }
60
62
61
63
// Setup suggestions
62
- val suggestionAdapter = SuggestionAdapter {
63
- searchBoxView.setText(it.query, true )
64
- }
65
- binding.suggestions.configureRecyclerView(suggestionAdapter)
64
+ val suggestionAdapter = SuggestionAdapter { searchBoxView.setText(it.query, true ) }
65
+ binding.suggestions.configure(suggestionAdapter)
66
66
connection + = suggestionSearcher.connectHitsView(suggestionAdapter) {
67
67
it.hits.deserialize(Suggestion .serializer())
68
68
}
69
69
70
- // Switch display depending search box focus
71
- searchBoxView.searchView.setOnQueryTextFocusChangeListener { _, hasFocus ->
72
- if (hasFocus) display(Display .Suggestions ) else display(Display .Hits )
70
+ // Show/Hide suggestions
71
+ suggestionSearcher.response.subscribe {
72
+ val visibility = if (it?.hits.isNullOrEmpty()) View .GONE else View .VISIBLE
73
+ binding.suggestionsGroup.visibility = visibility
73
74
}
74
75
75
76
// initial search
76
77
multiSearcher.searchAsync()
77
78
}
78
79
79
- private fun RecyclerView.configureRecyclerView (recyclerViewAdapter : RecyclerView .Adapter <* >) {
80
+ private fun RecyclerView.configure (recyclerViewAdapter : RecyclerView .Adapter <* >) {
80
81
visibility = View .VISIBLE
81
82
layoutManager = LinearLayoutManager (this @QuerySuggestionGuide)
82
83
adapter = recyclerViewAdapter
@@ -89,15 +90,4 @@ class QuerySuggestionGuide : AppCompatActivity() {
89
90
multiSearcher.cancel()
90
91
connection.clear()
91
92
}
92
-
93
- private fun display (display : Display ) {
94
- binding.suggestionsGroup.visibility = display.visibleIf(Display .Suggestions )
95
- binding.hitsGroup.visibility = display.visibleIf(Display .Hits )
96
- }
97
-
98
- private enum class Display {
99
- Suggestions , Hits ;
100
-
101
- fun visibleIf (display : Display ) = if (this == display) View .VISIBLE else View .GONE
102
- }
103
93
}
0 commit comments