Skip to content

Commit

Permalink
[Jetcaster] Use the ViewModel factory DSL (#1156)
Browse files Browse the repository at this point in the history
  • Loading branch information
bentrengrove authored Sep 13, 2023
2 parents e2c59af + 3467bac commit 1511471
Showing 1 changed file with 7 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ package com.example.jetcaster.util

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory

/**
* Returns a [ViewModelProvider.Factory] which will return the result of [create] when it's
Expand All @@ -26,22 +28,10 @@ import androidx.lifecycle.ViewModelProvider
* If the created [ViewModel] does not match the requested class, an [IllegalArgumentException]
* exception is thrown.
*/
fun <VM : ViewModel> viewModelProviderFactoryOf(
create: () -> VM
): ViewModelProvider.Factory = SimpleFactory(create)

/**
* This needs to be a named class currently to workaround a compiler issue: b/163807311
*/
private class SimpleFactory<VM : ViewModel>(
private val create: () -> VM
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
val vm = create()
if (modelClass.isInstance(vm)) {
@Suppress("UNCHECKED_CAST")
return vm as T
}
throw IllegalArgumentException("Can not create ViewModel for class: $modelClass")
inline fun <reified VM : ViewModel> viewModelProviderFactoryOf(
crossinline create: () -> VM
): ViewModelProvider.Factory = viewModelFactory {
initializer {
create()
}
}

0 comments on commit 1511471

Please sign in to comment.