Android Viewmodel

ViewModelのインスタンス化の仕方

MainActivityのonCreateで、 by viewModels()

としてインスタンス化すると、Activityが再度つくられたときも、最初にインスタンスがかえってくるため、値が保持できている

class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //var viewModel = UIViewModel()
        val viewModel: UIViewModel by viewModels()

        setContent {
            AppTheme {
                // A surface container using the 'background' color from the theme
                Surface(color = MaterialTheme.colors.background) {
                    //Greeting("Android")
                    KirokuScreen(viewModel)
                }
            }
        }
    }
}

ViewModel Overview | Android Developers

いろいろなやり方

Recommended Ways To Create ViewModel or AndroidViewModel - DEV Community

アプリケーションコンテキストなど必要な場合は

ViewModelでなくてAndroidViewModelをかわりにつかえる

android - Passing application to AndroidViewModel - Stack Overflow