android - 如何从另一个 viewModel 中的 viewModel 访问函数

标签 android android-studio kotlin mvvm

我有 2 个 View 模型 -

  1. 主视图模型**
  2. 存储 View 模型

StorageViewModel.kt

class StorageViewModel @ViewModelInject constructor(private val preferenceStorage: 
 PreferenceStorage, @ApplicationContext context: Context) : ViewModel() {

   ........
   //save last played song
   fun saveLastPlayedSong(song: Songs){
    viewModelScope.launch {
        protoDataStoreManager.saveLastPlayedSong(song)
     }
    }

  }

现在,我想在 MainViewModel 中调用 saveLastPlayedSong 函数

MainViewModel.kt

class MainViewModel @ViewModelInject constructor(
private val musicServiceConnection: MusicServiceConnection,
private val storageViewModel: StorageViewModel
) : ViewModel(){ 

 .........
 
fun playOrToggleSong(
    mediaItem: Songs, toggle: Boolean = false
)
{
    //here, I want to call the function from StorageViewModel e.g 
    storageViewModel.saveLastPlayedSong(mediaItem)  
  }
}

如何在 MainViewModel 中实例化“StorageViewModel”,什么是最佳方法(良好实践)。

我正在使用 MVVM 和 Hilt。

最佳答案

这通常是不良架构的症状。

如果 StorageViewModel 的行为类似于 Repository,则它不应扩展 ViewModel。如果它没有与 UI 的连接,您可以将它转换为存储库类,这将解决您的问题,因为它会变成一个可注入(inject)的单例。

如果 StorageViewModel 连接到 fragment (例如),您应该引用两个 View 模型并从 UI 层在它们之间传递数据。

类似于:

class StorageFragment : Fragment {
  private val storageViewModel: StorageViewModel by viewModels()
  private val mainActivityViewModel: MainViewModel by activityViewModels()

  //....

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    //you can do this if the song saving is a UI related thing
    //just have playOrToggleSong accept a function as parameter
    //as success callback
    button.setOnClickListener {
      mainActivityViewModel.playOrToggleSong(...) {
        storageViewModel.saveLastPlayedSong(param)
      }
    }
  }
}

关于android - 如何从另一个 viewModel 中的 viewModel 访问函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68401486/

相关文章:

java - 忽略 AndroidX 并希望在 Android Studio 3.2 中单独使用 android 支持库

Android Studio 构建失败,minSDK=29

android - Android Kotlin 中的 fragment 类型不匹配

android - 读取 QR 码导致 kotlin 应用程序崩溃

java - adb 无法连接到位于 tcp :5037 的守护程序

Android:自定义搜索栏缩略图显示不正确

android - 使用root清除状态栏通知

java - Android 保护 list admob

android - 如何让 Android Studio 停止在搜索结果中返回生成的代码?

android - 小数到粗俗分数,Kotlin Android