不确定这是否可能。然而,我正在寻找解决这一问题的方法。
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 (),因为只有当用户键入EditText时才能知道路径。
我不知道这是否可能。不过,我很想知道一个可能的解决方案。我甚至准备改变我的整体解决方案,如果它适合我的情况。
发布于 2020-04-04 07:18:48
您可以使用飞重工厂创建新的回购实例。如下所示:
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)
}
}https://stackoverflow.com/questions/61024797
复制相似问题