Hilt is a dependency injection library built on top of Dagger that simplifies the use of dependency injection in Android applications. Below are examples of how to integrate Hilt with various Android components.
To use Hilt in an Activity, you simply annotate the Activity with @AndroidEntryPoint. This will allow the Activity to request dependencies from the Hilt container.
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject lateinit var repository: MyRepository
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Now you can use the repository
}
}
Similarly, for Fragments, you also apply the @AndroidEntryPoint annotation.
@AndroidEntryPoint
class MyFragment : Fragment() {
@Inject lateinit var viewModelFactory: ViewModelFactory
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Use your ViewModel factory
}
}
To use Hilt with ViewModels, the ViewModel should use @HiltViewModel annotation. It allows Hilt to provide dependencies directly to the ViewModel.
@HiltViewModel
class MyViewModel @Inject constructor(
private val repository: MyRepository
) : ViewModel() {
// Your ViewModel code
}
To inject dependencies into a Service, apply the @AndroidEntryPoint annotation to the service class like this:
@AndroidEntryPoint
class MyService : Service() {
@Inject lateinit var repository: MyRepository
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
// Use your repository
return START_STICKY
}
}
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?