单击按钮时 Dagger 2 动态注入

Dagger 2 dynamic injection when button gets clicked

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

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 时才能知道该路径。

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

您可以使用 flyweight factory 创建新的 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)
    }
}