【问题标题】:How to access a function from a viewModel in another viewModel如何从另一个视图模型中的视图模型访问函数
【发布时间】:2021-09-24 19:33:06
【问题描述】:

我有 2 个视图模型 -

  1. MainViewModel**
  2. StorageViewModel

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。

【问题讨论】:

  • 如果对您有帮助,请您接受答案吗?这可以帮助其他人。

标签: android android-studio kotlin mvvm


【解决方案1】:

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

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

如果StorageViewModel 连接到片段(例如),您应该引用两个视图模型并从 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)
      }
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 2012-12-30
    • 2011-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多