If you’re creating a custom InstantSearch widget because you didn’t find a built-in option for your use case,
consider opening a feature request to describe what you’re trying to build.
-
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.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
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
Implement the view
Implement a
SumSearchesView:
it should display the data received in setSum and trigger the onReset when clicked.Kotlin
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
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
Final touches
You just created your first custom widget and you can now use it in your app like any other widget:Kotlin