Use Dagger 2 Map Multibinding to Inject Binders in Example Project #7
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
For Graywater to display an item, it needs to know how to map an item to
ViewHolderCreators
(for inflating the view) andBinders
(for binding the item to the view). In the middle areItemBinders
, which are simply lists ofBinders
that are needed for each item.Constructing the relationship between
ItemBinders
andBinders
is necessary during initialization, because the complement of supportedItemBinders
must be registered before items are added to the adapter. This can incur a large overhead if there are many types involved.This pull request specifies the dependencies using Dagger 2 modules and leaves it up to Dagger to resolve the dependency graph using multibindings.
There are 3 multibinding maps:
Map<Class<?>, ItemBinder>
Map<CreatorKey, ViewHolderCreator>
Map<Class<?>, ActionListener>
One may wonder why
Map<Class<?>, Binder>
is missing. It is unnecessary because the dependencies of everyItemBinder
is known at compile time, but it is unknown which ItemBinders will be used in a list, since the list is not built until runtime. More importantly, it is easier to inject aMap
than to inject each individual binder into the adapter.To further improve initialization performance, we only construct the binders that are visible on screen.
This works by changing
List<Binder>
to returnList<Provider<Binder>>
. Dagger 2 automatically supportsProvider<Binder>
, which allows us to defer the cost of binder initialization until the user scrolls. With the proper usage of scopes, extra initializations can be avoided.