0.基于Dager2.38.1的hilt源码-前言

前言

想了解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地址,可自行查看

  1. 在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() {...}
    
  2. viemodel上使用了@HiltViewModel修饰:

     @HiltViewModel
     class UserListViewModel @Inject constructor(
         private val userListRepository: UserListRepository
     ) : ViewModel() {...}
    
     @HiltViewModel
     class UserDetailsViewModel @Inject constructor(
         private val userDetailsRepository: UserDetailsRepository
     ) : ViewModel() {...}
    
  3. 这样操作就可以使用和Dagger一样注解了,DatabaseModule和NetworkModule;

     @InstallIn(SingletonComponent::class)
     @Module
     object DatabaseModule {
         @Provides
         @Singleton
         fun provideAppDatabase(@ApplicationContext appContext: Context): UsersDatabase {
             return Room.databaseBuilder(
                 appContext,
                 UsersDatabase::clas
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值