首页 > 解决方案 > 使用 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
    }
}

标签: androidmvvmdependency-injectionretrofit2dagger-hilt

解决方案


我终于能够找到解决问题的方法。我向视图模型添加了一个字段,以及一个为该字段设置值的方法。基本上,我调用 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)
        }
    }
}

推荐阅读