0

The lambda parameter in viewModels() method is a factory itself, so why google requires us to create a factory for the factory? Is it just an api fault or an intended decision?

I made a wrapper, which allows to pass parameters to the ViewModel much easier without creating a special factory. Are there any drawbacks of this solution?

class UserActivity {
    val user by lazy { intent.getSerializableExtra("user") as User }
    val viewModel by easyViewModels { UserViewModel(user) }

    inline fun <reified T : ViewModel> easyViewModels(noinline factory: () -> T) = viewModels<T> {
        object : ViewModelProvider.Factory {
            override fun <S : ViewModel?> create(modelClass: Class<S>) = factory() as S
        }
    }
}

The reason for that is that I'm trying to integrate Dagger with Jetpack ViewModels. There is an another solution with multi binding: Inject property into ViewModel using Dagger 2, but it doesn't work with the assisted injection feature. So I made it the following way:

class UserActivity : AppCompatActivity() {
    @Inject
    lateinit var userViewModelFactory: UserViewModel.Factory

    val user by lazy { intent.getSerializableExtra("user") as User }
    val viewModel by easyViewModels { userViewModelFactory.create(user) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_user)
        DaggerAppComponent.create().inject(this)
    }
}
class UserViewModel @AssistedInject constructor(
    val userUsecase: UserUsecase,
    @Assisted val user: User
) : ViewModel() {

    @AssistedFactory
    interface Factory {
        fun create(user: User): UserViewModel
    }
}

Is it correct?

pavelperc
  • 119
  • 5
  • 1
    Read comments and answers from this - https://stackoverflow.com/questions/54419236/why-a-viewmodel-factory-is-needed-in-android – Rajasekhar Apr 16 '21 at 13:09
  • @Rajasekhar I have seen this question. I don't argue with the necessity of the Factory. I just say, that the lambda in my example already acts as a factory. – pavelperc Apr 16 '21 at 13:28

0 Answers0