Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ViewModelProviders is updated with ViewModelProvider #2974

Merged
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import javax.inject.Inject
import javax.inject.Provider

Expand All @@ -37,8 +36,22 @@
/** Instantiates a new instance of the specified view model, injecting required dependencies. */
override fun <T : ViewModel> create(modelClass: Class<T>): T {
val creator =
creators[modelClass] ?: throw IllegalArgumentException("Unknown model class $modelClass")
return creator.get() as T
creators[modelClass]
?: creators.entries.firstOrNull { modelClass.isAssignableFrom(it.key) }?.value
?: error("Unknown model class $modelClass")
try {
val viewModel = creator.get()
if (modelClass.isInstance(viewModel)) {
@Suppress("UNCHECKED_CAST")
return viewModel as T
} else {
error(
"Expected instance of ${modelClass.simpleName}, but got ${viewModel::class.simpleName}"
)
}
} catch (e: Exception) {
throw ViewModelCreationException("Failed to create ViewModel for class $modelClass", e)
}
anandwana001 marked this conversation as resolved.
Show resolved Hide resolved
}

/**
Expand All @@ -47,12 +60,15 @@
*/
operator fun <T : ViewModel> get(fragment: Fragment, modelClass: Class<T>): T =
if (modelClass.getAnnotation(SharedViewModel::class.java) == null) {
ViewModelProviders.of(fragment, this)[modelClass]
ViewModelProvider(fragment, this)[modelClass]
} else {
get(fragment.requireActivity(), modelClass)
}

/** Returns an instance of the specified view model scoped to the provided activity. */
operator fun <T : ViewModel> get(activity: FragmentActivity, modelClass: Class<T>): T =
ViewModelProviders.of(activity, this)[modelClass]
ViewModelProvider(activity, this)[modelClass]
}

class ViewModelCreationException(message: String, cause: Throwable? = null) :
Exception(message, cause)

Check warning on line 74 in ground/src/main/java/com/google/android/ground/ui/common/ViewModelFactory.kt

View check run for this annotation

Codecov / codecov/patch

ground/src/main/java/com/google/android/ground/ui/common/ViewModelFactory.kt#L73-L74

Added lines #L73 - L74 were not covered by tests
Loading