Created
January 23, 2023 04:41
-
-
Save AdnanHabibMirza/70f9b2915cb098df8ee6c57f4875b251 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import androidx.compose.runtime.Composable | |
import androidx.compose.ui.platform.LocalContext | |
import androidx.hilt.navigation.HiltViewModelFactory | |
import androidx.lifecycle.ViewModel | |
import androidx.lifecycle.ViewModelProvider | |
import androidx.lifecycle.ViewModelStoreOwner | |
import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner | |
import androidx.lifecycle.viewmodel.compose.viewModel | |
import androidx.navigation.NavBackStackEntry | |
@Composable | |
inline fun <reified VM : ViewModel> keyedHiltViewModel( | |
key: String? = null, | |
viewModelStoreOwner: ViewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) { | |
"No ViewModelStoreOwner was provided via LocalViewModelStoreOwner" | |
} | |
): VM { | |
val factory = createKeyedHiltViewModelFactory(viewModelStoreOwner) | |
return viewModel(viewModelStoreOwner, factory = factory, key = key) | |
} | |
@Composable | |
@PublishedApi | |
internal fun createKeyedHiltViewModelFactory( | |
viewModelStoreOwner: ViewModelStoreOwner | |
): ViewModelProvider.Factory? = if (viewModelStoreOwner is NavBackStackEntry) { | |
HiltViewModelFactory( | |
context = LocalContext.current, | |
navBackStackEntry = viewModelStoreOwner | |
) | |
} else { | |
// Use the default factory provided by the ViewModelStoreOwner | |
// and assume it is an @AndroidEntryPoint annotated fragment or activity | |
null | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment