android - 为什么我在 android 中需要 ViewModelFactory?

标签 android kotlin mvvm viewmodel android-viewmodel

我正在尝试在 ViewModel 类中传递一个构造函数参数。但我不明白这样做的最佳方法。请看一下代码和评论,让我知道最简单和合适的方法。

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    // Question 1: How can I pass constructor parameter if I use this delegate feature?
    // private lateint var viewModel: MainViewModel by viewModels()

    private lateinit var viewModel: MainViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val repository = Repository()

        // Passing constructor directly works.
        viewModel = MainViewModel(repository)

        // Question 2: Why do I need this factory class / method as it works without these two lines.

//        val viewModelFactory = MainViewModelFactory(repository)
//        viewModel = ViewModelProvider(this, viewModelFactory).get(MainViewModel::class.java)


        viewModel.getPost()
        viewModel.mResponse.observe(this, Observer { response ->
            if (response.isSuccessful) {
                Log.d("Response: ", response.body()?.userId.toString())
                Log.d("Response: ", response.body()?.id.toString())
                binding.textView.text = response.body()?.title.toString()
                Log.d("Response: ", response.body()?.body.toString())
            } else {
                Log.d("Response: ", response.errorBody().toString())
                binding.textView.text = response.code().toString()
            }
        })

    }
}

最佳答案

// Question 1: How can I pass constructor parameter if I use this delegate feature?
// private lateint var viewModel: MainViewModel by viewModels()

您会将您的 ViewModelFactory 作为 a parameter to viewModels() 传递.或者,根据参数的性质,使用依赖倒置框架(Dagger/Hilt、Koin 等)。在您的情况下,您似乎正在传递某种存储库,在这种情况下,依赖倒置框架是一种流行的解决方案。

   // Question 2: Why do I need this factory class / method as it works without these two lines.

因为它实际上不起作用。特别是,MainViewModel 实例无法在配置更改(例如,屏幕旋转)后继续存在。如果您想正确使用 Jetpack ViewModel 系统,ViewModel 系统必须实例化您的 MainViewModel

关于android - 为什么我在 android 中需要 ViewModelFactory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69508208/

相关文章:

java - Android:强制音频到耳机 >> setDeviceConnectionState 失败:java.lang.NoSuchMethodException:

java - android 尝试在空对象引用上调用虚拟方法 'void android.app.ActionBar.setHomeButtonEnabled(boolean)'

java - 如何将点击监听器添加到 Android/Java Textview 中的字符串中?

android - 如何在 Kotlin 中抛出 HttpException - 改造 2 - 单元测试

kotlin - 如何向 kotlin 协程发出 postman 请求

c# - 首次加载时 WPF 验证未触发

c# - WPF Caliburn.Micro 和 TabControl - 更改选项卡,不更改模型

android - 我在布局 Activity 中看不到我添加的图片

android - 使用扩展方法的 Kotlin 数据绑定(bind)

c# - 每个 View 模型的 Autofac 实例