简体   繁体   中英

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. why ?

onCreate() of Fragment

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.

this is about your implementation of ViewModelProvider . use this way for creating your 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 的上下文。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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