Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Dagger 2 - Patryk Poborca

Dagger 2 - Patryk Poborca

An attempt at a presentation explaining how to implement Dagger 2 without using Thermosiphons and Coffee machines as examples. Link to corresponding repo:
github.com/patrykpoborca/CleanArchitecture

Patryk Poborca

October 22, 2015
Tweet

Other Decks in Programming

Transcript

  1. Dependency Injection aka (DI) Ugh, sounds complicated. So let’s get

    started and talk about what DI is, and how to use Dagger 2. To first understand DI, you must understand the principle of inversion of control. In essence it’s the idea that your class should be given any (complex) classes it depends on, and not create them. Dependency Injection is a software design pattern that implements inversion of control for resolving dependencies.
  2. DAG Is formed by a collection of vertices and directed

    edges, each edge connecting one vertex to another, such that there is no way to start at some vertex v and follow a sequence of edges that eventually loops back to v again. ~Wikipedia
  3. Let’s build out a TweeterAPI application We write our own

    “apis” and not utilize actual APIs: OKHttp - For fake requests Retrofit - To fake processing requests (Constructor takes OKHttp) LocalDataCache - To fake writing to disk (LDC takes Context in Constructor) TweeterAPI - The goal of our little application (Takes Retrofit and LocalDatacache)
  4. Local data module We’re providing a LocalDataCache for anyone that

    might need it. Notice, because in my Appmodule I specifically exposed “Application” this param must= Application
  5. Generating files... Dagger parses your dependencies, and finds out what

    is exposed, what is not, determines what can be provided, and generates builders for your components.
  6. The step from just Factory to DI Dagger 2 generates

    a complex structure behind the scenes which also contains a factory, allowing you to do things like this: CleanArchitectureApplication.getTweeterAPIComponent() . getTwitterAPI();
  7. We must strive to be better Allows us to inject

    any dependencies from BaseComponent
  8. So…. where does TweeterAPI Come in? As you may have

    observed, I never made a method in my NetworkModule which provides a TweeterAPI This is because Dagger 2 can infer what it can provide based on objects with injectable constructors, so if you look back at the implementation of TweeterAPI you can inject that object into your code:
  9. Scopes So currently, each time you inject an Activity you

    will likely be instantiating a new TweeterAPI/OKHttp/Retrofit instance. That’s where scope comes in. You simply tag your components and Modules with an annotation.