android - 为什么 Dagger Factory 方法不像 Builder 那样工作?
问题描述
在我的 Android 项目和app
模块中,我有一个登录屏幕。我想通过匕首提供它的视图模型。但是,null
尽管我清楚地定义了如何在模块类中生成它,但总是如此。这是我的代码:
class AuthViewModel(
private val firebaseAuth: FirebaseAuth,
private val logger: Logger
) {
....
}
这是模块对象。
@Module
object AuthModule {
@Provides
@JvmStatic
fun provideLogger(): Logger = getLogger() // It creates a Logger object forsure. I confirm it doesn't return null.
@Provides
@JvmStatic
fun provideViewModel(firebaseAuth: FirebaseAuth, logger: Logger) = AuthViewModel(firebaseAuth, logger)
@Provides
@JvmStatic
fun provideFirebaseAuth() = FirebaseAuth.getInstance()
}
这是组件
@FeatureScope
@Component(modules = [AuthModule::class])
interface AuthComponent {
@Component.Factory
interface Factory {
fun create(
@BindsInstance context: Context
): AuthComponent
}
}
这就是我将它注入我的活动的方式。
class AuthActivity : AppCompatActivity() {
@Inject lateinit var vm: AuthViewModel
@Inject lateinit var logger: Logger
companion object {
private val TAG = AuthActivity::class.java.simpleName
fun startActivity(ctx: Context) {
val intent = Intent(ctx, AuthActivity::class.java)
ctx.startActivity(intent)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
DaggerAuthComponent.factory()
.create(this)
logger.logDebug("test") // <==== Crashes here because logger is null
}
}
应用程序在上面的标记行崩溃,因为 logger 是null
. 我调试了应用程序并注意到 ViewModel 也为空。
解决方案
我不知道究竟是什么问题,但我用 Builder 替换了 Factory,我的问题得到了解决。
欢迎您告诉我原始代码中的问题,我将非常乐意接受您的回答。谢谢你。
@FeatureScope
@Component(modules = [AuthModule::class])
interface AuthComponent {
@Component.Builder
interface Builder {
fun build(): AuthComponent
@BindsInstance fun activity(context: Context): Builder
}
fun inject(activity: AuthActivity)
}
推荐阅读
- php - 使用 php 数组 shuffle 我的号码仍在重复。解决方案?
- python - 加权循环有向图中的最长路径
- python - Python - 在多线程应用程序中检测键盘中断
- android - razorpay android集成中的upi支付出现错误
- android - 将arraylist json解析为单个对话框
- java - 是否有一种 O(n) 方法来查找数组中某个值的所有索引?
- javascript - 从一种形式更改为另一种形式显示该形式中所有输入的“不可聚焦”错误
- php - 运行删除方法时未删除 Laravel 相关模型
- android-emulator - Genymotion 卡在“启动”/启动设备
- wordpress - 由于 URL 结构,Wordpress 联系表 7 不起作用