简体   繁体   English

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

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

Example, If I replaced 'fragmentA' with 'fragmentB', the 'viewModelA' of fragmentA is still live.例如,如果我用 'fragmentB' 替换了 'fragmentA',fragmentA 的 'viewModelA' 仍然有效。 why ?为什么 ?

onCreate() of Fragment片段的 onCreate()

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

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

ViewModel视图模型

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
        }
    }
}
}

This method used to replace fragment此方法用于替换片段

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()
}

You will note the while loop inside the Coroutine still work although after replace fragment to another fragment.您会注意到 Coroutine 中的 while 循环仍然有效,尽管在将片段替换为另一个片段之后。

this is about your implementation of ViewModelProvider .这是关于您的ViewModelProvider实现。 use this way for creating your viewModel.使用这种方式来创建您的 viewModel。

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

in this way you give your fragment as live scope of view model.通过这种方式,您将片段作为视图模型的实时范围。

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

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

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