Easier creation of Dagger ObjectGraph scopes with Retrofit and Butterknife niceties

Overview

Android Arsenal Scopes

###What is Scopes?

Have you ever tried to set up scoped ObjectGraphs with Dagger and failed miserably? Scopes is a compile time annotation processor that is here to help!

###What does Scopes do? It allows to separate portions of your Application in logical "flows". It generates "BaseActivitys" that contain common dependencies that other Activities that are part of the same flow could use.

###What the hell are you talking about?! Here is an example. Let's say that your Application has a login/signup flow (i.e. a screen with a login button, a another one with an "Enter username and password", etc). It is really likely that Activities that are part of this flow will have common dependencies (i.e. an AuthenticatorService.java,LoginErrorDialog.java, etc). Scopes allows you to define a BaseActivity that contains all these shared dependencies.

###Ok, got it, how do I use it? It all starts by defining a class that is Annotated with @DaggerScope; it does not need to be an Activity. If you decide not to annotate your Activity, the class annotated with @DaggerScope has to be in the same package as the Activity that extends the generated BaseActivity (huh?!... Look at the app module and you will see what I mean).

@DaggerScope(baseActivityName = "BaseLoginFlowActivity", retrofitServices = GithubService.class,
    restAdapterModule = RestAdapterModule.class, butterKnife = true)
public class LoginFlow {}

baseActivityName is the name you want to give to the parent Activity (it should be distinct for all BaseActivities)

retrofitServices takes in an array of Class Objects that are the retrofit interfaces you have defined

restAdapterModule is a Module that contains a provider for the RestAdapter to be used to create the retrofitServices

butterKnife it is an optional field that tells Scopes to wire up ButterKnife on the BaseActivity.

Once you build your project, Scopes will generate BaseLoginFlowActivity.java with the following content:

package me.emmano.scopes.app.login;

import android.app.Activity;
import android.os.Bundle;
import dagger.ObjectGraph;
import butterknife.ButterKnife;
public abstract class BaseLoginFlowActivity extends Activity {
  @javax.inject.Inject
  protected me.emmano.scopes.app.services.GithubService githubService;

  private ObjectGraph scopedObjectGraph;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(getLayout());
    ButterKnife.inject(getActivity());
    scopedObjectGraph = ((me.emmano.scopes.app.ScopedApplication)getApplication()).getObjectGraph().plus(new me.emmano.scopes.app.login.BaseLoginFlowActivityModule()).plus(getModules());
    scopedObjectGraph.inject(this);
  }
  @Override
  protected void onDestroy() {
    scopedObjectGraph = null;
    super.onDestroy();
  }
  protected abstract Object[] getModules();
  protected abstract Activity getActivity();
  protected abstract int getLayout();
}

As you can see Scopes creates BaseLoginFlowActivityModule.java that contains @Providers for the retrofitServices. This class uses the RestAdapter you provided to @DaggerScope to create the retrofitServices. If you did not provide a RestAdapter, Scopes assumes your Application Class has a module that will provide a RestAdapter. You will have to add @ApplicationGraph to a public method that returns the Application's ObjectGraph. In any way, you have to supply a RestAdapter one way or another. (more about @ApplicationGraph below)

package scopes;

import services.GithubService;
import retrofit.RestAdapter;
@dagger.Module(injects = me.emmano.scopes.app.BaseLoginFlowActivity.class, includes = modules.RestAdapterModule.class)
public class BaseLoginFlowActivityModule {
  @dagger.Provides
  public GithubService providesGithubService(RestAdapter adapter) {
    return adapter.create(services.GithubService.class);
  }
}

This is all fine and great, but what else do I have to do?

Now, you have to make your Activity extends the BaseActivity generated by Scopes; in this case it will be BaseLoginFlowActivity. You will have to implement a couple methods, in this case:

protected abstract Object[] getModules();
protected abstract Activity getActivity();
protected abstract int getLayout();

Here is a basic example of a class that extends BaseLoginFlowActivity:

package me.emmano.scopes.app;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.util.List;

import butterknife.InjectView;
import modules.ActivityModule;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import me.emmano.scopes.app.BaseLoginFlowActivity;
import services.Repo;


public class MainActivity extends BaseLoginFlowActivity {

    @InjectView(R.id.text)
    protected TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        textView.setText("Eureka!");
        githubService.starGazers(new Callback<List<Repo>>() {
            @Override
            public void success(List<Repo> repos, Response response) {
                for (Repo repo : repos) {
                    Log.e(MainActivity.class.getSimpleName(), repo.getLogIn());
                }
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    @Override
    protected Object[] getModules() {
        return new Object[]{new ActivityModule()};
    }

    @Override
    protected Activity getActivity() {
        return this;
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }
}

There is one last thing for you to do. getModules() gives you the option to add extra dependencies to be used just in this class (namely, MainActivity). The most simplistic implementation of a Module could be as follows:

package modules;

import dagger.Module;
import me.emmano.scopes.app.login.MainActivity;
import scopes.BaseLoginFlowActivityModule;

@Module(injects = MainActivity.class, addsTo = BaseLoginFlowActivityModule.class)
public class ActivityModule {}

Please note addsTo. Unfortunately, you will have to manually add the Module to which we are plus()sing. This will always be the Module generated by Scope that is injected on the BaseActivity; BaseLoginFlowActivityModule in this case.

What if I want Scopes to use dependencies from my Application's ObjectGraph?!

That is what @ApplicationGraph is for. Let's say you have dependencies that are common to your whole application (i.e. a Bus, a RestAdapter, etc) and you want your scoped graphs to have these dependencies; after all, this is what scopes are about. How do I do it? here is how:

@ApplicationGraph(applicationModule = ApplicationModule.class)
public ObjectGraph getObjectGraph() {return objectGraph;}

You can name this method whatever you like, but it must be public and reside inside your Application class. ApplicationModule is the module that contains the @Providers for dependencies that are common for the whole Application

TODO

Tons of refactoring. Kittens are currently dying due to some code on the ScopeProcessor class.

Add a parameter to @DaggerScope that allows passing an Classes[] to be injected on the BaseActivity. Right now, only Retrofit services can be injected. You can currently add these dependencies to your version of ActivityModule, add the corresponding @Injects and extends your version of MainActivity to get regular Objects other than retrofitServices injected. It is hacky and nasty, I know.

###Installation Just add the dependency to your build.gradle:

implementation 'me.emmano:scopes:0.1.5'
apt 'me.emmano:scopes-compiler:0.1.5@jar'

Scopes requires the apt plugin. You can add it easily by adding this to your build.gradle:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'
    }
}

apply plugin: 'com.android.application'
apply plugin: 'android-apt'

Lastly, add this inside android{} in your build.gradle:

packagingOptions {
    exclude 'META-INF/services/javax.annotation.processing.Processor'
}

For more help setting up Scopes you can look at the app sample module.

License

The MIT License (MIT)

Copyright (c) 2014 Emmanuel Ortiguela

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
You might also like...
Rolling Scopes School - Android 2021 - Stage 1 - Task 2 - Quiz
Rolling Scopes School - Android 2021 - Stage 1 - Task 2 - Quiz

rsschool2021-Android-task-quiz Rolling Scopes School - Android 2021 - Stage 1 - Task 2 - Quiz ☝️ Во втором практическом задании создадим приложение-кв

Android Studio plug-in for generating ButterKnife injections from selected layout XML.
Android Studio plug-in for generating ButterKnife injections from selected layout XML.

ButterKnifeZelezny Simple plug-in for Android Studio/IDEA that allows one-click creation of Butterknife view injections. How to install in Android Stu

Small training project where dagger, dagger hilt and other components are used for clean architecture
Small training project where dagger, dagger hilt and other components are used for clean architecture

LeagueNow 🏆 LeagueNow is a sample soccer team list Android application 📱 built to demonstrate use of modern Android development tools - (Kotlin, Arc

It is far easier to design a class to be thread-safe than to retrofit it for thread safety later
It is far easier to design a class to be thread-safe than to retrofit it for thread safety later

"It is far easier to design a class to be thread-safe than to retrofit it for thread safety later." (Brian Goetz - Java concurrency: Publisher: Addiso

MVVM RECIPE ANDROID APP Is an app where I show how to use MVVM, retrofit, dagger hilt, coroutine, liveData, Kotlin, navigation component, and so on...
MVVM RECIPE ANDROID APP Is an app where I show how to use MVVM, retrofit, dagger hilt, coroutine, liveData, Kotlin, navigation component, and so on...

MVVM RECIPE ANDROID APP Is an app where I show how to use MVVM, retrofit, dagger hilt, coroutine, liveData, kotlin, navigation component, and so on...

A clean architecture example. Using Kotlin Flow, Retrofit and Dagger Hilt, etc.
A clean architecture example. Using Kotlin Flow, Retrofit and Dagger Hilt, etc.

android-clean-architecture A clean architecture example. Using Kotlin Flow, Retrofit and Dagger Hilt, etc. Intro Architecture means the overall design

🔥Simple quote app using MVVM, Retrofit, Coroutines and Dagger Hilt 💉

🔥 simple quote app using MVVM, Retrofit, Coroutines and Dagger Hilt 💉 quote.mp4 📚 knowledges and technologies ViewBinding Retrofit Coroutines MVVM

Instagram clone App in android using Kotlin, LiveData, MVVM, Dagger, RxJava and Retrofit.
Instagram clone App in android using Kotlin, LiveData, MVVM, Dagger, RxJava and Retrofit.

Instagram-Project-in-android-with-MVVM-architecture Project from MindOrks Professional Bootcamp with self practice work and added some additional feat

A quiz app built with trivia api. This app was built with mvvm architecture, dagger-hilt, retrofit, room database, and navigation components.
A quiz app built with trivia api. This app was built with mvvm architecture, dagger-hilt, retrofit, room database, and navigation components.

A quiz app built with trivia api. This app was built with mvvm architecture, dagger-hilt, retrofit, room database, and navigation components.

Integration of Retrofit and Hilt-Dagger with MVVM architecture to get request from GitHub Api

GitHubApiApp-MVVM-Retrofit-Hilt-Dagger-Livedata 🎈 I built this project to demonstrate integration of Hilt-Dagger and Retrofit with MVVM architecture.

Android Viper template with Kotlin, Dagger 2, Retrofit & RxJava
Android Viper template with Kotlin, Dagger 2, Retrofit & RxJava

Android VIPER Architecture Example This repository contains a detailed sample client-server app that implements VIPER(View-Interactor-Presenter-Entity

 🍲Foodium is a sample food blog Android application 📱 built to demonstrate the use of Modern Android development tools - (Kotlin, Coroutines, Flow, Dagger 2/Hilt, Architecture Components, MVVM, Room, Retrofit, Moshi, Material Components).  🍲Foodium is a sample food blog Android application 📱 built to demonstrate the use of Modern Android development tools - (Kotlin, Coroutines, Flow, Dagger 2/Hilt, Architecture Components, MVVM, Room, Retrofit, Moshi, Material Components).
Dagger Hilt, MVP Moxy, Retrofit, Kotlin coroutine, Sealed class

Dagger Hilt, MVP Moxy, Retrofit, Kotlin coroutine, Sealed class

An example of a test task for creating a simple currency converter application for the Android platform. The app is developed using Kotlin, MVI, Dagger Hilt, Retrofit, Jetpack Compose.
An example of a test task for creating a simple currency converter application for the Android platform. The app is developed using Kotlin, MVI, Dagger Hilt, Retrofit, Jetpack Compose.

Simple Currency Converter Simple Currency Converter Android App by Isaev Semyon An example of a test task for creating a simple currency converter app

Finder Job simple app using (Retrofit , Dagger hilt , coroutines , navigation components)
Finder Job simple app using (Retrofit , Dagger hilt , coroutines , navigation components)

Job Finder I'm finished building a simple project Job Finder App technology used [dagger hilt, coroutines, navigation components, LiveData, Skelton pa

Aplicación android con MVVM, Room, Retrofit y Dagger Hilt, coonsumiento la API de TMDB.

TMDB Aplicación android con MVVM, Room, Retrofit y Dagger Hilt, coonsumiento la API de TMDB. To-Do: ☑ Diseño de aplicación con MVVM e inyeccion de dep

Educational App made with Retrofit, Coroutines, Navigation Component, Room, Dagger Hilt, Flow & Material Motion Animations.
Educational App made with Retrofit, Coroutines, Navigation Component, Room, Dagger Hilt, Flow & Material Motion Animations.

TechHub TechHub is a sample educational app that provides courses for people who want to learn new skills in mostly tech-related areas. The goal of th

This Project for how to use  MVVM , state flow, Retrofit, dagger hit, coroutine , use cases with Clean architecture.
This Project for how to use MVVM , state flow, Retrofit, dagger hit, coroutine , use cases with Clean architecture.

Clean-architecture This Project for how to use MVVM , state flow, Retrofit, dagger hit, coroutine , use cases with Clean architecture. Why i should us

Owner
null
The dependency injection Dagger basics and the concepts are demonstrated in different branches

In this project we will look at the dependency injection Dagger basics and the concepts are demonstrated in different branches What is an Dependency?

Lloyd Dcosta 6 Dec 16, 2021
Bind Android views and callbacks to fields and methods.

Butter Knife Attention: This tool is now deprecated. Please switch to view binding. Existing versions will continue to work, obviously, but only criti

Jake Wharton 25.7k Jan 3, 2023
Bind Android views and callbacks to fields and methods.

Butter Knife Attention: This tool is now deprecated. Please switch to view binding. Existing versions will continue to work, obviously, but only criti

Jake Wharton 25.7k Mar 22, 2021
A fast dependency injector for Android and Java.

Dagger A fast dependency injector for Java and Android. Dagger is a compile-time framework for dependency injection. It uses no reflection or runtime

Google 16.9k Jan 5, 2023
A fast dependency injector for Android and Java.

Dagger 1 A fast dependency injector for Android and Java. Deprecated – Please upgrade to Dagger 2 Square's Dagger 1.x is deprecated in favor of Google

Square 7.3k Jan 5, 2023
Guice (pronounced 'juice') is a lightweight dependency injection framework for Java 6 and above, brought to you by Google.

Guice Latest release: 5.0.1 Documentation: User Guide, 5.0.1 javadocs, Latest javadocs Continuous Integration: Mailing Lists: User Mailing List Licens

Google 11.7k Jan 1, 2023
A multi-purpose library containing view injection and threading for Android using annotations

SwissKnife A multi-purpose Groovy library containing view injection and threading for Android using annotations. It's based on both ButterKnife and An

Jorge Martin Espinosa 251 Nov 25, 2022
:syringe: Transfuse - A Dependency Injection and Integration framework for Google Android

Transfuse Transfuse is a Java Dependency Injection (DI) and integration library geared specifically for the Google Android API. There are several key

John Ericksen 224 Nov 28, 2022
DI can be simple. Forget about modules and components. Just use it!

PopKorn - Kotlin Multiplatform DI PopKorn is a simple, powerful and lightweight Kotlin Multiplatform Dependency Injector. It doesn't need any modules

Pau Corbella 145 Dec 25, 2022
A library which will save you a lot of time from writing the same intent creation code. it consist of many intent creation codes like Share, Contacts, Email and etc, which you can easily use.

Android-Intent-Library A library which will save you a lot of time from writing the same intent creation code. it consist of many intent creation code

Next 67 Aug 24, 2022