AppViewModelProvider.kt 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /*
  2. * Copyright (C) 2023 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * https://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.example.modifier.ui
  17. import android.app.Application
  18. import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory
  19. import androidx.lifecycle.createSavedStateHandle
  20. import androidx.lifecycle.viewmodel.CreationExtras
  21. import androidx.lifecycle.viewmodel.initializer
  22. import androidx.lifecycle.viewmodel.viewModelFactory
  23. import com.example.modifier.MyApplication
  24. import com.example.modifier.ui.backup.BackupViewModel
  25. /**
  26. * Provides Factory to create instance of ViewModel for the entire Inventory app
  27. */
  28. object AppViewModelProvider {
  29. val Factory = viewModelFactory {
  30. // Initializer for ItemEditViewModel
  31. initializer {
  32. BackupViewModel(
  33. this.createSavedStateHandle(),
  34. myApplication().container.backupItemDao
  35. )
  36. }
  37. // Initializer for ItemEntryViewModel
  38. }
  39. }
  40. /**
  41. * Extension function to queries for [Application] object and returns an instance of
  42. * [InventoryApplication].
  43. */
  44. fun CreationExtras.myApplication(): MyApplication =
  45. (this[AndroidViewModelFactory.APPLICATION_KEY] as MyApplication)