【问题标题】:@injection of constructor is not work in Android构造函数的@injection 在Android中不起作用
【发布时间】:2021-12-16 09:06:06
【问题描述】:

我正在尝试使用 Hilt 注入数据结构,但编译器说:

@HiltViewModel annotated class should contain exactly one @Inject annotated constructor.

我不明白为什么,也许我误用了 Hilt 的一些代码。

这是我的视图模型:

@HiltViewModel
class AccountProfileViewModel @Inject constructor() {

    @Inject
    lateinit var userProfile: UserProfileMemorySource

UserProfileMemorySource 看起来像这样:

@Singleton
class UserProfileMemorySource @Inject constructor() : UserProfileInterface{

    private var userProfile: UserProfile? = null

    override fun getUserProfile(): UserProfile? {
        return this.userProfile
    }

    override fun saveUserProfile(userProfile: UserProfile?) {
        this.userProfile = userProfile
    }

    override fun invalidate() {
        userProfile = null
    }

}

而数据类使用的是

data class UserProfile(
    val name: UserName? = null,
    val email: String = "",
    val phone: String = "",
    val address: Address? = null,
    val url: String = ""
)

我正在尝试将数据保存到内存中。

知道为什么它不起作用吗? 谢谢

【问题讨论】:

    标签: android kotlin dagger dagger-hilt


    【解决方案1】:

    依赖应该通过构造函数传递

    @HiltViewModel
    class AccountProfileViewModel @Inject constructor(
        private val userProfile: UserProfileMemorySource
    ) { 
    ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多