Why should I use viewmodelproviders for viewmodels?

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.

Upvotes: 5

Views: 1267

Answers (1)

EpicPandaForce
EpicPandaForce

Reputation: 81588

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.

Upvotes: 8

Related Questions