单击按钮时 Dagger 2 动态注入

钱德拉·塞卡

不确定是否可能。但是,我正在寻找解决此问题的方法。

class User(val name: String, val email: String)

class MyActivity : AppCompatActivity {
    @Inject lateinit var vm: MyViewModel

    override fun onCreate(bundle: Bundle?) {
        DaggerMyActivityComponent.create().inject(this)
        super.onCreate(bundle)
        setContentView(R.layout.activity_my)

        myButton.setOnClickListener {
            vm.insert(pathEditText.text.toString(), User("test name", "test email"))
        }
    }
}

class MyViewModel @Inject constructor(val repo: MyRepository) {
    fun insert(path: String, user: User) {
        repo.insert(user)
    }
}

class MyRepository(path: String) {
    val collection = Firebase.firestore.collection(path)

    fun insert(user: User) {
        collection.set(user)
    }
}

@Component(modules = [MyModule::class])
interface MyActivityComponent {
    fun inject(activity: MyActivity)
}

@Module class MyModule {
    @Provides fun repo() = MyRepository(How do I get the path here?)
}

问题:

我如何动态地将路径注入到 MyModule 的 @Provides fun repo() 中,因为只有在用户键入 EditText 时才能知道路径。

我不确定这是否可能。但是,很想知道一个可能的解决方案。如果适合我的情况,我什至准备更改我的整体解决方案。

巴瓦加

您可以使用享元工厂来创建新的 repo 实例。像这样:

class MyRepositoryFactory {

  fun create(path: String): MyRepository {
    return MyRepository(path)
  }

}

@Module class MyModule {
    @Provides fun repoFactory() = MyRepositoryFactory()
}

class MyViewModel @Inject constructor(val repoFactory: MyRepositoryFactory) {
    fun insert(path: String, user: User) {
        repoFactory.create(path).insert(user)
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章