繁体   English   中英

为什么在 Android 中替换当前片段后,我的 ViewModel 仍然存在?

[英]Why my ViewModel is still alive after I replaced current fragment in Android?

例如,如果我用 'fragmentB' 替换了 'fragmentA',fragmentA 的 'viewModelA' 仍然有效。 为什么 ?

片段的 onCreate()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    viewModel = ViewModelProvider.NewInstanceFactory().create(InvoicesViewModel::class.java)
}

视图模型

class InvoicesViewModel : ViewModel() {

init {
    getInvoices()
}

private fun getInvoices() {

    viewModelScope.launch {

        val response = safeApiCall() {
            // Call API here
        }

        while (true) {
            delay(1000)
            println("Still printing although the fragment of this viewModel destroied")
        }

        if (response is ResultWrapper.Success) {
            // Do work here
        }
    }
}
}

此方法用于替换片段

fun replaceFragment(activity: Context, fragment: Fragment, TAG: String) {
    val myContext = activity as AppCompatActivity
    val transaction = myContext.supportFragmentManager.beginTransaction()
    transaction.replace(R.id.content_frame, fragment, TAG)
    transaction.commitNow()
}

您会注意到 Coroutine 中的 while 循环仍然有效,尽管在将片段替换为另一个片段之后。

这是关于您的ViewModelProvider实现。 使用这种方式来创建您的 viewModel。

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    viewModel = ViewModelProvider(this).get(InvoicesViewModel::class.java)
}

通过这种方式,您将片段作为视图模型的实时范围。

检查您是否在 Activity 中创建了 ViewModel 并传递了 Activity 或 Fragment 的上下文。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM