前言
想了解hilt源码必须对Dagger的使用有所了解,否则将会感觉说的云里雾里。
当前hilt源码在应用上相对来说比Dagger简化很多,所以使用方便。but,他还是转换成Dagger形式,所以从源码的角度来说做的比Dagger感觉还要多。代码理解起来自然不容易。
Dagger案例
先看下Dagger的案例,为下面的Hilt做一个铺垫。
@Module(subcomponents = Subcomponent1.class,Subcomponent2.class,Subcomponent3.class)
public class Module{
@Provides
@Singleton
public A bindingMethod(B b){
return new A(b);
}
}
@Component(modules = Module.class)
public calss Component{
inject(MembersInjector m);
public SubcomponentX getSubcomponentX();//这个也是一个Subcomponent节点
}
public class MembersInjector{
@Inject
public C C;
}
@Singleton
public class C {
@Inject
public C(){}
}
hilt 使用Demo引发的不归路
实现声明:为了方便我们的理解,以下的代码是进过我个人简化再简化得来的案例。实际hilt源码比这个零散的多,而且理解困难的多。
hilt demo
demo地址,可自行查看
-
在Application(用户自定义,命名确实比较骚)使用@HiltAndroidApp修饰,Activity和Fragment使用@AndroidEntryPoint修饰:
@HiltAndroidApp class Application : Application() { override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } } } @AndroidEntryPoint class MainActivity : AppCompatActivity(R.layout.activity_main) @AndroidEntryPoint class UserListFragment : Fragment() {...} @AndroidEntryPoint class UserDetailsFragment : Fragment() {...}
-
viemodel上使用了@HiltViewModel修饰:
@HiltViewModel class UserListViewModel @Inject constructor( private val userListRepository: UserListRepository ) : ViewModel() {...} @HiltViewModel class UserDetailsViewModel @Inject constructor( private val userDetailsRepository: UserDetailsRepository ) : ViewModel() {...}
-
这样操作就可以使用和Dagger一样注解了,DatabaseModule和NetworkModule;
@InstallIn(SingletonComponent::class) @Module object DatabaseModule { @Provides @Singleton fun provideAppDatabase(@ApplicationContext appContext: Context): UsersDatabase { return Room.databaseBuilder( appContext, UsersDatabase::clas