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
MyWidgetView
interface, describing the rendering of the widget data.- Implement your view in a
MyWidgetViewImpl
that you’ll use.
- Implement your view in a
-
Create the
Connection
s between yourViewModel
and the other components:- Create a
MyWidgetConnectionView
to connect yourViewModel
to 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 ViewModel
Our ViewModel
will be quite straightforward: it stores a sum
that can be increment
ed or reset
ed to 0.
We 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
Implementing our View
We can now implement a SumSearchesView
: it should display the data received in setSum
and trigger the onReset
when clicked.
Kotlin
Create the ConnectionView
To link our ViewModel
and its View
, we will 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 ConnectionSearcher
Because our 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
Convenient functions
To simplify usage of the widget, you will create two extension functions that connect theViewModel
to other components:
Kotlin
Final touches
You just created your first custom widget and you can now use it in your application like any other widget:Kotlin