android - 使用 HILT 时将整数传递给 ViewModel
问题描述
我试图弄清楚如何在使用刀柄时将整数从片段传递到视图模型。我已经准备好可以为此使用视图模型工厂,我不确定如何使用 DI 来完成。
在下面的代码中,我试图弄清楚如何将 albumId 传递给 viewModel。从 API 端点获取数据时将使用 albumId。
分段
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_album_details, container, false)
val albumId = arguments?.getInt("album_id")
viewModel.songs.observe(viewLifecycleOwner) {
view.song_recyclerview.apply {
layoutManager = LinearLayoutManager(this.context)
adapter = SongAdapter(viewModel.songs)
}
}
return view
}
视图模型
class SongViewModel @ViewModelInject constructor(
songRepo: SongRepository,
@Assisted savedStateHandle: SavedStateHandle
) : ViewModel(), LifecycleObserver {
val songs: LiveData<List<Song>> = songRepo.getSongs(1)
}
存储库
class SongRepository constructor(
private val musicService: MusicService
)
{
fun getSongs(album_id: Int): LiveData<List<Song>> {
val data = MutableLiveData<List<Song>>()
musicService.getAlbumTracks(album_id).enqueue(object : Callback<List<Song>> {
override fun onResponse(call: Call<List<Song>>, response: Response<List<Song>>) {
data.value = response.body()
}
override fun onFailure(call: Call<List<Song>>, t: Throwable) {
}
})
return data
}
}
解决方案
我终于能够找到解决问题的方法。我向视图模型添加了一个字段,以及一个为该字段设置值的方法。基本上,我调用 viewModel.start(int) 然后调用 viewModel.songs。
视图模型
class SongViewModel @ViewModelInject constructor(
songRepo: SongRepository,
@Assisted savedStateHandle: SavedStateHandle
) : ViewModel(), LifecycleObserver {
private val _id = MutableLiveData<Int>() // int field
private val _songs = _id.switchMap { id ->
songRepo.getSongs(id)
}
val songs: LiveData<List<Song>> = _songs
fun start(id: Int) { // method to update field
_id.value = id
}
}
分段
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// get data from bundle and pass to start()
arguments?.getInt(("album_id"))?.let { viewModel.start(it)}
viewModel.songs.observe(viewLifecycleOwner) {
view.song_recyclerview.apply {
layoutManager = LinearLayoutManager(this.context)
adapter = SongAdapter(viewModel.songs)
}
}
}
推荐阅读
- r - 如何正确应用 RowMeans()?“X 不是数字”错误
- html - 无法实现特定的 CSS 网格布局
- php - Laravel 弹性搜索
- javascript - Trix 编辑器定义自定义附件样式
- rally - 在 Lookback API 中查找最新的 ScheduleState 更改
- python - 如果为空、空白或具有“N/A”,则跳过记录
- reactjs - 如何在反应中映射某个组件中的所有输入
- android - 有没有办法在 android studio 中找到所有 Log.d() 行
- javascript - 来自动态生成的输入的 vue.js 绑定值
- voronoi - Houdini voronoifracture 组