CustomView dependency injection with dagger 2 (within activity scope)

前端 未结 2 1386
广开言路
广开言路 2021-02-02 13:04

My question is similar to this.

So for instance, I have a LiveData implementation:

public class CustomLiveData extends LiveData

        
相关标签:
2条回答
  • 2021-02-02 13:41

    tl;dr Don't inject model layer dependencies inside custom View objects

    Subclasses of View are not good targets for Dagger 2 injection. View objects are meant to be drawn and not must else, hence the name "view". The constructors for View should make this clear; they are designed for inflating View objects from attributes specified in XML. In other words, a View object should be able to be specified in a layout.xml file, inflated at the appropriate point in the lifecycle, and then obtained using findViewById(int id), Butterknife or data binding. In this way, the best custom View objects take no dependencies.

    If you want to link a View and some data from the model layer, the standard pattern is to write an Adapter like those for RecyclerView and ListView. If this is not possible, using a setter (e.g., setData()) is preferable to passing dependencies from the model layer in the constructor or requesting injection from within one of the lifecycle methods of the View.

    If instead you inject your LiveData object inside an Activity or Fragment using the AndroidInjector class the correct Context will be provided without you having to do anything. This explains your comment "I don't get any compiler complaints if CustomLiveData is injected into MainActivity instead into the view."

    Once you have injected the LiveData object into the Activity, use one of the above methods (an adapter or a setter) to associate the data with your custom View. See the Google Android Architecture example here where elements from the model layer are injected using Dagger 2 and then associated with a ListView using findViewById and setAdapter()

    Link to the Dagger 2 issue where injection of View objects is discussed:

    https://github.com/google/dagger/issues/720

    0 讨论(0)
  • 2021-02-02 13:52

    Your Dagger hierarchy looks like this: appcomponent -> activitycomponent

    You try to inject activity context inside view, that depends on appcomponent directly.

    It's not possible since there is no method that could provide activity context in appcomponent. Instead, inside view, you should retrieve activity (for example using getContext), extract activitycomponent from it and only then inject CustomLiveData.

    0 讨论(0)
提交回复
热议问题