1

在这个工厂中,我需要使用 Retrofit 从 api 获取我的数据并将缓存与空间一起存储,我的存储库规则这个应用程序!我有存储库暂停功能,负责获取我的数据,一些保存/更新数据获取和保存/更新需要不同的值才能运行,我不知道(还)如何在 Kodein 中配置它我缺乏解决这个问题的经验而且我在 Stackoverflow 中找不到任何可以帮助我的东西。

我试图将变量 ID:String 和编辑的实体 (CampaignEntry) 添加到定义中,它符合但在运行时崩溃

No binding found for bind<CampaignEditViewModelFactory>() with ? { String -> ? }

我的主要应用程序 bind() 使应用程序崩溃

class MarketingApplication : Application(), KodeinAware {
    override val kodein = Kodein.lazy {
        import(androidXModule(this@MarketingApplication))
...
bind() from factory { id: String, campaignEntry: CampaignEntry -> 
            CampaignEditViewModelFactory(id, campaignEntry, instance()) }
...

我的 ViewModel - 必须在一个 ViewModel 中传递不同调用所使用的变量 id 和 campaignEntry 可能是问题所在 - 但我无法找出正确的解决方案。

class CampaignEditViewModel(
    private val id: String,
    private val campaignEntry: CampaignEntry,
    private val marketingRepository: MarketingRepository
) : ViewModel() {
    val campaignToSave by lazyDeferred { marketingRepository.updateCampaign(campaignEntry) }
    val campaignToEdit by lazyDeferred { marketingRepository.getCampaignById(id) }
}

为了清楚起见,我的lazyDeferred

fun <T> lazyDeferred(block: suspend CoroutineScope.() -> T): Lazy<Deferred<T>> {
    return lazy {
        GlobalScope.async(start = CoroutineStart.LAZY) {
            block.invoke(this)
        }
    }
}

存储库快照

interface MarketingRepository {
...
    suspend fun getCampaignById(campaignId: String): LiveData<CampaignEntry>
    suspend fun updateCampaign(campaignEntry: CampaignEntry): LiveData<CampaignEntry>
...

我像这样从我的片段中调用 Viewmodel

class CampaignEditFragment : ScopedFragment(), KodeinAware {
    override val kodein by closestKodein()
    private val viewModelFactoryInstanceFactory: ((String) -> CampaignEditViewModelFactory) by factory()
...
private fun bindUI() = launch {
        val campaignVM = campaignEditViewModel.campaignToEdit.await()
...
    btn_edit_save.setOnClickListener {it: View
                saveCampaign(it)
...
private fun saveCampaign(it: View) = launch {
        campaignEditViewModel.campaignToSave.await()
    }

最后是 ScopedFragment

abstract class ScopedFragment : Fragment(), CoroutineScope {
    private lateinit var job: Job

    override val coroutineContext: CoroutineContext
        get() = job + Dispatchers.Main

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        job = Job()
    }

    override fun onDestroy() {
        super.onDestroy()
        job.cancel()
    }
}

如果您需要更多代码 - 请询问

4

1 回答 1

0

由于您绑定了 2 个参数,因此您需要使用factory2

private val viewModelFactoryInstanceFactory: ((String, campaignEntry) -> CampaignEditViewModelFactory) by factory2()
于 2019-08-13T12:47:02.220 回答