You are trying to create your own widget with InstantSearch Android and that’s awesome. But that also means that you couldn’t find the widgets or built-in options you were looking for. Algolia would love to hear about your use case as the aim with the InstantSearch libraries is to provide the best out-of-the-box experience. Don’t hesitate to send a quick message explaining what you were trying to achieve either using the form at the end of that page or directly by submitting a feature request.
-
Create the
MyWidgetViewModel, containing the business logic for your widget. -
Create a
MyWidgetViewinterface, describing the rendering of the widget data.- Implement your view in a
MyWidgetViewImplthat you’ll use.
- Implement your view in a
-
Create the
Connections between yourViewModeland the other components:- Create a
MyWidgetConnectionViewto connect yourViewModelto itsView. - If it uses the
Searcher, create aMyWidgetConnectionSearcher. - If it uses the
FilterState, create aMyWidgetConnectionFilterState.
- Create a
Example
You’ll build a widget that displays the number of searches made since it was last clicked.1
Create the view model
The
ViewModel will be quite straightforward: it stores a sum that can be incremented or reseted to 0.
It will use InstantSearch’s SubscriptionValue to allow subscribing to changes of the sum’s value.Kotlin
2
Create the view interface
To interact with the data in our
ViewModel, you need a view than can display a number, and handle clicks for resetting.Kotlin
3
Implement the view
Implement a
SumSearchesView:
it should display the data received in setSum and trigger the onReset when clicked.Kotlin
4
Create the connection view
To link the
ViewModel and its View,
define a connection to describe what should happen when connecting (subscribe to sum and set the reset callback) and when disconnecting (unsubscribe to sum and remove the callback).Kotlin
5
Create the connection searcher
Because the widget needs to be aware of searches to count them,
it needs to be connected to a
Searcher.Subscribe to its response to call increment() on every new search response.Kotlin
6
Create helper functions
To simplify usage of the widget,
create two extension functions that connect the
ViewModel to other components:Kotlin
Final touches
You just created your first custom widget and you can now use it in your app like any other widget:Kotlin