Dagger 2 is a popular dependency injection framework for Android. Integrating Dagger 2 with other Android components, such as Activities, Fragments, and Services, allows for better code organization and easier management of dependencies.
To integrate Dagger 2 with an Activity, follow these steps:
@Module
class MainActivityModule {
@Provides
fun provideGreeting(): String {
return "Hello, Dagger!"
}
}
@Component(modules = [MainActivityModule::class])
interface MainActivityComponent {
fun inject(activity: MainActivity)
}
class MainActivity : AppCompatActivity() {
@Inject lateinit var greeting: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
DaggerMainActivityComponent.create().inject(this)
Toast.makeText(this, greeting, Toast.LENGTH_SHORT).show()
}
}
The integration process for Fragments is similar:
@Module
class FragmentModule {
@Provides
fun provideDependency(): SomeDependency {
return SomeDependency()
}
}
@Component(modules = [FragmentModule::class])
interface FragmentComponent {
fun inject(fragment: MyFragment)
}
class MyFragment : Fragment() {
@Inject lateinit var dependency: SomeDependency
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
DaggerFragmentComponent.create().inject(this)
// Use dependency...
return inflater.inflate(R.layout.fragment_layout, container, false)
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?