[英]Why my ViewModel is still alive after I replaced current fragment in Android?
例如,如果我用 'fragmentB' 替换了 'fragmentA',fragmentA 的 'viewModelA' 仍然有效。 为什么 ?
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.