Skip to content

Instantly share code, notes, and snippets.

@robotsquidward

robotsquidward/01.kt Secret

Last active Sep 28, 2020
Embed
What would you like to do?
class MyActivity : AppCompatActivity() {
private val model: MyViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
model.getUsers().observe(this, Observer<List<User>>{ users ->
// update UI
})
}
}
fun createWithFactory(
create: () -> ViewModel
): ViewModelProvider.Factory {
return object : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")// Casting T as ViewModel
return create.invoke() as T
}
}
}
private val model: MyViewModel by lazy {
ViewModelProvider(
this,
createWithFactory {
MyViewModel(repo = MyRepository())
}
).get(MyViewModel::class.java)
}
private val model: MyViewModel by activityViewModels {
createWithFactory {
MyViewModel(repo = MyRepository())
}
}
/**
* Get a [ViewModel] in an [ComponentActivity].
*/
@MainThread
inline fun <reified VM : ViewModel> ComponentActivity.viewModelBuilder(
noinline viewModelInitializer: () -> VM
): Lazy<VM> {
return ViewModelLazy(
viewModelClass = VM::class,
storeProducer = { viewModelStore },
factoryProducer = {
return@ViewModelLazy object : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")// Casting T as ViewModel
return viewModelInitializer.invoke() as T
}
}
}
)
}
/**
* Get a [ViewModel] in a [Fragment].
*/
@MainThread
inline fun <reified VM : ViewModel> Fragment.activityViewModelBuilder(
noinline viewModelInitializer: () -> VM
): Lazy<VM> {
return ViewModelLazy(
viewModelClass = VM::class,
storeProducer = { requireActivity().viewModelStore },
factoryProducer = {
object : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")// Casting T as ViewModel
return viewModelInitializer.invoke() as T
}
}
}
)
}
private val model: MyViewModel by viewModelBuilder {
MyViewModel(repo = MyRepository())
}
private val model: MyViewModel by activityViewModelBuilder {
MyViewModel(repo = MyRepository())
}
dependencies {
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment