Why should I use viewmodelproviders for viewmodels?

谁说我不能喝 提交于 2020-05-09 05:45:32

问题


Why should I use viewmodelproviders for viewmodels?

Why I just can't add custom singleton annotation to my viewmodel, and then inject this viewmodel to fragment class?

Like so:

@MainScope
class MainViewModel @Inject constructor(): ViewModel()

And then:

open class BaseFragment<T: ViewModel>: DaggerFragment() {
@Inject
protected lateinit var viewModel: T

Both cases are independent of screen rotation.

Is there any drawbacks of singleton annotation case? I see only advantages, with this approach I don't need to copy/paste tons of code.


回答1:


Why should I use viewmodelproviders for viewmodels?

To get viewModel.onCleared() callback called properly at the right time by the ComponentActivity.

(and to ensure it's created only once for the given ViewModelStoreOwner).

Why I just can't add custom singleton annotation to my viewmodel, and then inject this viewmodel to fragment class?

Because you won't get viewModel.onCleared() callback called properly at the right time by the ComponentActivity.

Is there any drawbacks of singleton annotation case? I see only advantages,

That you don't get viewModel.onCleared().

Also if you have a singleton variant, then the ViewModel won't die along with its enclosing finishing Activity, and stay alive even on back navigation (which is probably not intended).

with this approach I don't need to copy/paste tons of code.

You're using Kotlin. Use extension functions.



来源:https://stackoverflow.com/questions/58189456/why-should-i-use-viewmodelproviders-for-viewmodels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!