Issue
Basically there are two ways which i know of:
- Pass the dependency through newInstance
- Retrieve the depencency through onAttach
Both methods seem to get the job done.
However the first method, is very much like the usual way of declaring dependencies through a constructor, but it requires the passed dependency to implement the Parcelable interface, which is not always possible, or wanted. (eg. database DAO and repository)
The second method retrieves the dependencies when it gets attach to a context. This way it's possible to ask the context if it has, certain dependencies needed for the fragment to function. It seems like a very clean and efficient way, but the problem with this is it hides dependencies, and makes it harder to test.
So my question is this: Is there a third way? Or is there some way to make either method have the best of both worlds?
Solution
You can use Dagger 2 to inject dependencies into your fragment. After you have set it up, you can just annotate a member of your fragment with the @Inject
annotation and Dagger 2 will provide an instance of a required class. And it's possible to replace your dependencies in tests.
Answered By - makovkastar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.