Sobes.tech
Junior — Middle

At what level are you familiar with Dagger 2 principles and usage in Android development?

sobes.tech AI

Answer from AI

Dagger 2 is a dependency injection library for Android applications that manages the creation and provision of objects, improving code modularity and testability.

At the junior/middle level, I am familiar with the basic principles of Dagger 2:

  • Using @Module annotations to define dependency providers.
  • @Provides annotation within modules to describe methods that create objects.
  • @Component annotation to connect modules and injection points.
  • Dependency injection via constructors or fields using @Inject.

Example of a simple module and component:

@Module
class NetworkModule {
    @Provides
    fun provideHttpClient(): OkHttpClient {
        return OkHttpClient.Builder().build()
    }
}

@Component(modules = [NetworkModule::class])
interface AppComponent {
    fun inject(activity: MainActivity)
}

class MainActivity : AppCompatActivity() {
    @Inject lateinit var client: OkHttpClient

    override fun onCreate(savedInstanceState: Bundle?) {
        DaggerAppComponent.create().inject(this)
        super.onCreate(savedInstanceState)
        // now the client is ready to use
    }
}

Thus, Dagger 2 helps automatically create and provide dependencies, reducing component coupling and making code maintenance easier.