Skip to content

Instantly share code, notes, and snippets.

@VitalyPeryatin
Created July 6, 2022 19:54
Show Gist options
  • Save VitalyPeryatin/ad3348170981c58923d68189426b73a3 to your computer and use it in GitHub Desktop.
Save VitalyPeryatin/ad3348170981c58923d68189426b73a3 to your computer and use it in GitHub Desktop.
SharedViewModel (Compose Navigation)
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