Skip to content

Instantly share code, notes, and snippets.

@VitalyPeryatin
Created July 6, 2022 19:14
Show Gist options
  • Save VitalyPeryatin/c0ec7841b8c5f0098dc3aa64532beb33 to your computer and use it in GitHub Desktop.
Save VitalyPeryatin/c0ec7841b8c5f0098dc3aa64532beb33 to your computer and use it in GitHub Desktop.
SharedViewModelHolder (Compose)
// Inner navigation graph
val sharedViewModelHolder = SharedViewModelHolder<PostCreateViewModel>()
navGraphBuilder.navigation(
route = PostCreateDestination.RootCreatePostRoute,
startDestination = PostCreateDestination.SelectCreatablePost.createRoute()
) {
composable(PostCreateDestination.SelectCreatablePost) {
SelectCreatablePostScreen(
modifier = modifier,
navController = navController,
sharedViewModel = sharedViewModelHolder.createNewSharedViewModel()
)
}
composable(PostCreateDestination.CreatePost) { navBackStackEntry ->
val arguments: PostCreateDestination.CreatePost.Arguments =
PostCreateDestination.CreatePost.rememberArguments(navBackStackEntry)
PostCreateScreen(
modifier = modifier,
navController = navController,
sharedViewModel = sharedViewModelHolder.getSharedViewModel(),
type = arguments.nonNullablePostType
)
}
composable(PostCreateDestination.ChooseSpace) {
ChooseSpaceScreen(
modifier = modifier,
navController = navController,
sharedViewModel = sharedViewModelHolder.getSharedViewModel()
)
}
}
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.lifecycle.ViewModel
import org.koin.androidx.compose.getViewModel
import java.lang.ref.WeakReference
class SharedViewModelHolder<T: ViewModel> {
var sharedViewModelReference = WeakReference<T>(null)
}
@Composable
inline fun <reified T: ViewModel> SharedViewModelHolder<T>.createNewSharedViewModel(): T {
val viewModel: T = getViewModel()
LaunchedEffect(Unit) {
if (sharedViewModelReference.get() !== viewModel) {
sharedViewModelReference = WeakReference(viewModel)
}
}
return viewModel
}
@Composable
inline fun <reified T : ViewModel> SharedViewModelHolder<T>.getSharedViewModel(): T {
return sharedViewModelReference.get() ?: getViewModel()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment