Concepts / Building Search UI / Create your own widgets
Jan. 07, 2019

Create your own widgets

If none of the existing widgets fit your use-case, you can implement your own!

You are trying to create your own widget with Android InstantSearch and that’s awesome 🎉. But that also means that you couldn’t find the widgets or built-in options you were looking for. We’d love to hear about your use case as our mission with our InstantSearch libraries is to provide the best out-of-the-box experience. Don’t hesitate to send us a quick message explaining what you were trying to achieve either using the form at the end of that page or directly by submetting a feature request

Any View in your Activity implementing one or more widget interfaces will be picked up by InstantSearch at instantiation. Most widgets will implement two methods:

A more advanced widget will implement the AlgoliaSearcherListener interface to get a reference to the Searcher used in your search interface. It will enable your widget to uses the Searcher’s programmatic API.

Using the Searcher

The Searcher is responsible for connecting your search interface to your Algolia application. It wraps an Algolia API Client and provides a level of abstraction over it.

Diagram searcher

The Searcher handles all search requests: when Searcher#search() is called, the Searcher will fire a request with the current query, and will forward the search results to its listeners.

Diagram listeners

Once your widget implements AlgoliaSearcherListener, it can use the Searcher to interact with the state of the search interface: add new facets, refine on a value, know if there are more results to load, …

Using the Events

InstantSearch comes with an event system that lets you react during the lifecycle of a search query:

  • when a query is fired via a SearchEvent(Query query, int requestSeqNumber)
  • when its results arrive via a ResultEvent(JSONObject content, Query query, int requestSeqNumber)
  • when a query is cancelled via a CancelEvent(Request request, Integer requestSeqNumber)
  • when a request errors via a ErrorEvent(AlgoliaException error, Query query, int requestSeqNumber)
  • when a new facet refinement is applied via a FacetRefinementEvent(Operation operation, NumericRefinement refinement)
  • when a new numeric refinement is applied via a NumericRefinementEvent(Operation operation, String attribute, String value)

We use EventBus to dispatch events. You can register an object to the event bus using EventBus.getDefault().register(this); after which it will receive events on methods annotated by @Subscribe:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Logger {
    Logger() {
        EventBus.getDefault().register(this);
    }

    @Subscribe
    onSearchEvent(SearchEvent e) {
        Log.d("Logger", "Search:" + e.query);
    }

    @Subscribe
    onResultEvent(ResultEvent e) {
        Log.d("Logger", "Result:" + e.query);
    }
}

Did you find this page helpful?