algolia / instantsearch-ios

⚡️ A library of widgets and helpers to build instant-search applications on iOS.
https://www.algolia.com/doc/guides/building-search-ui/what-is-instantsearch/ios/
Apache License 2.0
591 stars 55 forks source link

Feat: adds clear function to HitsSource #265

Open NicFontana opened 1 year ago

NicFontana commented 1 year ago

Summary This PR adds a clear() function to HitsSource protocol that can be used to clear the data source's memory, if desired.

Motivation: HitsObservableController has a @Published public var hits: [Hit?] property that can be set empty to show an empty result list. For instance, we can set it empty if we want to clear the results list for any reason, and not just when a query becomes empty by leveraging the showItemsOnEmptyQuery property of HitsInteractor.Settings.

Result As a result we have a reduced memory consumption when we assign an empty array to HitsObservableController's hits and whenever desired.

I also added a couple of tests that cover the new introduced code.

I hope this can be useful and the same result is not achievable in another way, otherwise, I apologize.

Please let me know if I missed something.

Thank you

VladislavFitz commented 1 year ago

Thank your for your PR, @NicFontana !

HitsObservableController has a @Published public var hits: [Hit?] property that can be set empty to show an empty result list.

This assumption is not consistent with the InstantSearch architecture. The source of truth containing the information about the current state of Hits is the HitsInteractor. You are not supposed to change the @Published public var hits: [Hit?] property manually. HitsObservableController is just a "read-only" adapter ensuring the compatibility with SwiftUI, but unfortunately this cannot be ensured via the type system.

If you want to clear your hits view manually, you might do it by changing the HitsInteractor state. The HitsInteractor instance will automatically update all the connected HitsController implementations, including HitsObservableController instances.

However, there is actually no simple way to reset the HitsInteractor state. So, my suggestion is to keep the clear methods for HitsInteractor and Paginator classes and to cancel changes in the HitsSource and HitsObservableController controller classes. Wdyt?

NicFontana commented 1 year ago

Hello @VladislavFitz

Thanks for your feedback, I followed your suggestions in the last commit.

I also marked with private(set) the HitsObservableController @Published properties. This should help making HitsObservableController consistent with InstantSearch's architecture:

The source of truth containing the information about the current state of Hits is the HitsInteractor. You are not supposed to change the @Published public var hits: [Hit?] property manually. HitsObservableController is just a "read-only" adapter ensuring the compatibility with SwiftUI, but unfortunately this cannot be ensured via the type system.