🗡Dagger HILT: Cómo hacer INYECCIÓN de DEPENDENCIAS en Android ⚡

Honestly, I don’t care if you learn Dagger Hilt today or not, what I want you to have is this Hi DevExperto in the video of last week with all the new features of Android 11, many of you asked me to speak on a particular subject So today I decided to create a video with all the information we have about it and this issue is no more and no less that Dagger Hilt Dagger Hilt is a dependency injection library which has been created by Google and is therefore the official recommendation for implement the injection in Android applications Dagger Hilt is still an Alpha, so what I’m going to tell you today is my first impressions using it, but I don’t recommend using it at all It’s your decision now If you want to risk using an Alpha on your projects in production or not But why now Hilt’s? The truth is that the Android community has been a little lost for a long time with how to implement dependency injection into Android Dagger has almost always been the choice for most of the applications, but it is true that it is a very complex library and that each he uses it a little bit in his own way, because there’s never been an official guide to tell us how best to use it That’s why the Android community is already I’ve been asking Google for quite some time to take a position on this issue And we finally have Dagger Hilt here Google’s bid to inject dependencies into Android applications But why do I need Dagger, Hilt or any dependency injector in my applications? For that we have to go back to what it is a dependency injector and what needs it covers And honestly, I don’t care if you learn Dagger Hilt today or not, what I want you to have is this A dependency injector is an entity in your application that provides the facilities that other entities are going to need, but surely this won’t say anything, so let’s start at the beginning Usually when you start worrying about the quality of your software, you need to start creating entities and modules that do one thing This is what is known as the principle of sole responsibility for the SOLID and is one of the most important concepts within programming This principle tells us that if an entity does only one thing, then he’ll only have one reason to change and he’ll be much more independent of all the external factors that occur in our application A stand-alone unit is much easier to modify, replace and test If you don’t know much about the SOLID principles, I’m going to leave you here in the description and in the first comment a link to download a guide free of charge about the principles and you can start applying them in your projects The principle of sole responsibility is vital, but it is also true that it increases the complexity of our code in one area in particular that is that of dependencies By having a lot of entities that have their own responsibility for form isolated, this makes the number of entities or modules in our application grows much faster The first thing we’ll do intuitively is create these modules that we need within our own entity Let’s imagine we have an entity that is a car and that you need to use another entity that’s a motor type Well, we will surely make a new Motor() inside the car Well, you know the Kotlin doesn’t exist, but it is to create a new entity and this will bring us two problems The first thing we’re not gonna know about entities depends on who is creating those news If we get into the code and read it everything from top to bottom, because we can really extract that information But ideally, from the outside, we should know which rooms that module with respect to the rest of the modules of our application And on the other hand, if we want to modify those dependencies during the tests, we’re not going to have it easy either because we don’t have any way to replace it To be able to isolate that module and test it independently from the other modules, this is where the investment of dependencies comes to the rescue How about instead of creating us the premises are provided to us in some way? Normally, this provision of premises is made through the builder And that’s where we’re reversing the control of the premises, instead of us being the ones in charge of generating the dependencies, the premises are given to us as a builder This has two contrasting advantages with the two drawbacks we had before On the one hand, it is very clear to us in the builder which are the dependencies of that entity and on the other hand, in test time we can modify them without any problem, whether it’s a mock, a double of any kind Here’s a little digression, and that is to for this to be true, we would need a tool as Mockito is capable, we can create dependencies of any kind If we really want to replace him by any double test, what we really need is the inversion of dependencies, which is often confused with the reversal of control, but it’s not exactly the same thing The principle of inversion of dependencies is another of the SOLID principles, which is what it tells us is that instead to depend on concretions, we should depend on abstractions That is, instead of relying on classes the final ones, the ones that come to us from the builder, we should rely on interfaces or abstract classes so that we can then implement those interfaces and provide those doubles Or even in the future, if our application requires another

element to be able to change it without having to change that class But what’s going on here? That the provision of dependencies becomes super complex and therefore we have to consider other ways of promoting them We can’t just create those rooms anywhere because then it’s going to be very difficult to detect where we’re including them, how to modify them, and so on To do this, the ideal is to have a structure or other entity in our application to provide us with those facilities There are many supply systems of outbuildings, some more popular than others, and I don’t want to go into that today If you’re more interested in this topic, leave me a comment and I can talk of it in another video, but here we’re going to focus mainly in the injection of dependency Okay, so we’ve figured out the problem and we have understood that the solution is the injection of dependencies But what exactly is the injection of dependencies? Very broadly speaking, it would be the way automatic to provide the dependencies to our modules Imagine yourself as a bag of pieces that make up your application When we want to create a new piece, that piece will depend on others Then we’ll go to that sack We’ll look for the rooms we need and we’ll use those pieces to make the new bigger piece Once we have it created, that piece becomes part of the bag in case someone else needs it Dagger Hilt’s goal is to do this very simple and also integrated with the Android framework So now, if you will, we’re going to go into the code and show you how to integrate Hilt into an application This application I’m going to show you is part of my Architect Coders program, where I explain the injection of dependencies and I explain Dagger So I’m going from that point, from the point where I start using Dagger And what I’m going to do is transform it to use Hilt If you don’t know much about Dagger, don’t worry, because I’m not going to do a process here of migration very much in use, but I’m just going to substitute things But if you know Dagger, you’ll be able to link some concepts with others and understand much more quickly how Hilt works So let’s get to it Well, here’s our code Like I said, I’m not gonna explain much about how Dagger works, but If you know Dagger, I want to explain very quickly what I have here Simply a masterful film detail application When we click on a movie we navigate in detail and here in injection of dependencies we have If we go to the application we’ll see that we’ve created the Dagger component He’s compiling right now, but I don’t care because I don’t I’m going to use Dagger, I don’t want to dwell on it too much We see that we are creating the component here Then if we go to the dependency injection package, we have right here MyMoviesComponent That what he does is through one A Factory provides the application and then has a couple of its components Each of them is a component of scope of each of the activities, the main activity and the detail activity If you haven’t seen Dagger before, this means we’re going to have a major network that’s going to survive for the entire life of the application All those dependencies belong to the application and then we have a couple of modules, each dependent on the Activity corresponding, that those will only survive as long as survive the Activity, so that we can have dependencies that are unique or a kind of singleton, but only for the Activity Once the Activity dies, if another new Activity is created, this dependency is recreated in such a way that this is very useful for having singleton for scope Okay The app module has a series of dependencies and the data module too We’re not going into which rooms It’s because it’s not worth going too deep into what the code does either, simply in understanding how to implement this in our code So the first thing we have to do is add a series of dependencies I’m going to build.gradle and stick them here For example, here I don’t need this and I don’t need this Dagger’s, I’m taking them off, I synchronize these rooms and we’re gonna need a couple more things The first is to include the Kotlin here, KAPT And the second is to add a configuration for the KAPT which is KAPT correctErrorTypes = true This is a setup that I don’t quite know what it does to be sincere, but which requires Hilt to function properly It’s something about how he behaves KAPT when it finds a type error Now we would go to the main build.gradle and we would add a plug-in that we need for Hilt to work. It’s not absolutely necessary, but what does the code much easier, so I recommend you include it Once we have this, we’d go to the app and tell him we’re going to use Hilt

To do this, simply use a notation Let’s go here to the application and here what we would do is tell you this is going to be a Hilt Android App and that’s it With this we have all the configuration we need for Hilt If you were using Dagger, you’d know you had to stay here This component These Hilt He does it from behind, so we can forget all about this In fact, our Application stays on one line Let’s delete this line One important thing to keep in mind is that Hilt from behind does all the setting up on the onCreate So whenever we’re going to do something about Hilt and the classes of the Android framework, we’ll have to do it after we call to super oncreate(), because that’s where the magic happens Now we would create the modules that we go to use with Hilt, the modules that allow us to organize the units in a structured way, so that when that number of dependencies grows we have it organized and it’s much easier for us to understand where each unit stands In addition, if we use Android Studio modules, we can have for each Android Studio module a Hilt module And that way have very well defined what the dependencies of each module are within Android Studio Okay, I’m gonna go back to the modules I had before Dagger For example, the Application module is a module that has a number of dependencies related to topics of the Android framework and the Application in general For example, the module is a module that has a set of related to the Android framework mainly So here we have a series of dependencies databaseProvider that returns a MovieDatabase I want to make it clear why the guy here is going to be the one we use the most and to define a module we indicate it with the word @Module If you’ve used Dagger, you’ll know that every module is related to a component and that component we can define which is the area you will be using within the Dagger’s suite of dependencies In the case of Hilt we do not have custom components, but we have a series of components already predefined by default If you look over here I’m going to let you a box with all the components that exist that are among others application component activity component fragment component that allow us to define dependencies that are only going to live for the lifetime of that component In addition, each component provides us with implicitly a series of dependencies that can be very useful to us For example, the activity component gives us the activity or the fragment component gives us the fragment If you remember, for example, when in Dagger I had already created the application component through the Factory had to pass the application. Inside Hilt We don’t need to do that because the application component already implicitly provides us with the dependency both in terms of application and context, so that if we need it to use in one of the other rooms we already have available So back to the code here, as we indicate which component corresponds to this module, because all we have to do is use another notation called @InstallIn and define the component we want it to be installed on In our case it is the application component and tell him we passed him the class on that application component This module is already installed in the application component and those dependencies are already provided at application level to define a dependency within a module We use the same notes you’d know if you knew Dagger He provides us with an identification that we will provide a dependency and if we use singleton what it means is that every time we ask for that dependency, every time we go to the sack to get that piece, we’ll get the same piece every time If not when we go to the sack, every time we take that piece will be a new instance of the piece, but we won’t reuse it in our code So depending on whether we want using a single instance or several, we can do it this way This would be like the singleton pattern, but much better, because in testing time we can replace it without any problem How could we use these facilities? Well, we can use them in any point where we mark the class, like Android Entry Point These Android entry points They can only be of a few specific types activity, fragment, view, service and broadcast receiver Once we mark one of those classes as Android and Centric Point We can use the rooms that are in Hilt in a very simple way, using the @Inject notation So if we go to MainActivity, for the moment we’re going to take out this part we had before Dagger’s And if I wanted to use an outhouse, let’s put in this case that of the AppModule I want to get the movie database back So I would go to the MainActivity and do an ‘Inject lateinit var

This is necessary so that Dagger can inject dependency MovieDatabase type database and that’s it I don’t need anything else All I’d need to do is mark this Activity as an @AndroidEntryPoint, so that Hilt knows it has to inject dependencies here, but everything else is set up automatically If you’ve used Dagger you’ll know there’s a huge difference between what we’re doing with Hilt and the configuration required by Dagger But the most common thing is that for the activities we want to have modules that only survive for the life of that activity For this purpose, we can create modules specifics that use the Activity component So how do we do this? Well, if we leave To the injection of main dependencies and we come here to the MainActivityModule, we see that we have a number of dependencies What we’re missing here is a reminder of what we did on the application module is the first thing, the components we have already said are not used in Hilt We have a number of components by default, so we delete it and here we tell him to install in the component activity component So that the Activity that uses the rooms here These units will only survive the lifetime of that activity If ever these facilities required the Activity as such, we don’t need to inject it anywhere because automatically the activity component provides it to us And what about the ViewModel that I have here a bit abandoned? In this example I did it with one of the many ways there is to do it with Dagger We’ve already discussed that in Dagger there’s no official way to do things and it’s precisely the ViewModels have given a lot of headaches, but with Hilt Obviously this is taken care of That’s if it doesn’t come with Hilt by default, but you have to add an extra library on AndroidX and I’ll show you how to do it The first thing you need to do is add those new rooms So we’re going to build.gradle application and add them, for example here with the rest of the injector Most likely by adding these lines you need to add the above, but well, we’ll leave it at that for leaving Of course, these are specific to the ViewModel Also, if you want to make it even easier with Kotlin and use a delegate properties that exist on AndroidX, you would also need to add this the Activities department to provide us with that delegate This is optional, but it simplifies working with Kotlin For the integration with ViewModel to work, we have to do two things The first is to go to the ViewModel Let’s find the MainViewModel and do the inject on the builder For this we will use the @ ViewModelInject annotation And we tell him to inject the builder you know you have to add this dependency to the dependency injector The next modification is a bit subtle and is that we have to go to the Main Activity Module and modify the component in which we add it Right now we’re adding it to the Activity component and this means that these dependencies are going to survive only during the lifetime of the activity But many times we will be interested in their survival during their lifetime of the ViewModel, because the Activity can rotate the screen You can make different configuration changes, but we’ll probably continue to be interested until the Activity is dead Definitely that these units continue to exist because they’re going to be the same Then, instead of using the Activity Component we would use the ActivityRetainedComponent to inject the default Activity so that we have it available here The default injection is the ViewModel So if any of our units require ViewModel, we can retrieve it directly without having to explicitly provide it And that’s it With this we go to the MainActivity and instead of looking for ways a little bit of a stretch to do this, all we’d have to do is private val ViewModel MainViewModel type and we use the delegate viewModels, provided by the library we added earlier We simply don’t need to do anything more with this You know the builder you need to use is the one we’ve marked for injection And besides, those facilities are going to be provided by Hilt If we wanted to, we could keep doing it the old-fashioned way with ViewModelProvider of this, and we would pass you MainViewModel class.java, As you can see, nowhere do you have to create a factory to identify what

the builder we’re going to use, or anything like that It all works because of Hilt I personally prefer the top one because it’s cleaner and I can to make this property like Val, instead of having to make it like lateinit var And as you see here, nowhere else do we have to define anything on the component, nor create it, nor add it to the main component Hilt does all that for us, just as we have done with an Activity We could do it with a Fragment, with a View You see it’s super easy to integrate Hilt with the Android framework If you want to see the full example where I applied Hilt, I leave you in the description the Architect Coders repository in the specific branch where I’ve included it so you can see that migration from Dagger to Dagger Hilt Or if you didn’t know Dagger either worry because you can go straight to Hilt’s code And if any of these concepts about the SOLID principles does not finish you to be clear, don’t worry, because remember that both the description as in the first comment you have a link to download that guide and start applying it to your own projects In conclusion, my opinion of Hilt is which is a big step forward compared to what we had with Dagger, mainly because it lays the groundwork for how to perform the injection of dependencies in Android, something we didn’t have before and that every developer had to apply to his form And this is always such good news It also greatly simplifies the process with compared to what we had before with Dagger However, it’s still a little more complex than alternatives like Koin It’s true that there are some differences between these two bookstores I’ll leave you a video here in the box I already did in English where I explain how to use Koin But if you want me to do it in Spanish and compare them leave me a comment and I’ll think about it for future videos One of the issues that often concerns me a lot when I use libraries that are so tightly coupled to the Android framework is what’s going to happen if I have modules where I don’t have Android For example, a module that is only Java or just from Kotlin and where I don’t want the Android dependency I haven’t tried this yet, but I was talking to Manuel Vivo, which is devrel on Google and which has been part of this process of creating the and he told me there’s no problem, so I also if you’re interested in me making a video about this, tell me and I can dig deeper All in all, I like Dagger Hilt a lot It’s a big step forward and the only thing left to do is to see how the community adopts it if really works well on very large projects and if it doesn’t get relegated because to other alternatives or some of the existing ones This is only time will tell, but remember she’s an Alpha, so use it carefully in your projects, especially if they’re in production And if you want to know more about the rest of Android 11 news, you can see the full video here As always, subscribe here below hit the bell, like if you liked it and see you in the next video See you soon, DevExpert