【问题标题】:How to get the data from repository using viewmodel如何使用视图模型从存储库中获取数据
【发布时间】:2021-12-31 17:46:40
【问题描述】:

使用 Repository 时,我想使用 ViewModel 从 API 获取数据。

但是,我不明白如何配置ViewModel 以获取数据。通过查看我的代码让我知道我是否正确执行此操作。此外,学习推荐会很好,这就是我无法弄清楚的原因。我的基本编码技能需要提高吗?

这是AppModule

@Module
@InstallIn(SingletonComponent::class)
object AppModule {

    @Provides
    @Singleton
    fun providesPokemonRepository(
        api: MovieApiService
    ) = MovieRepository(api)

    @Singleton
    @Provides
    fun providesMovieApi(): MovieApiService {
        return Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(MovieApiService::class.java)
    }


}
This is the repository

class MovieRepository @Inject constructor(private val api: MovieApiService) {

    suspend fun getMovieLists(): Resource<List<MoviesItem>> {
        val response = try {
            api.getMovies()
        } catch (e: Exception) {
            return Resource.Error("An unknown error occurred")
        }
        return Resource.Success(response)
    }

}

这是我要配置的视图模型

@HiltViewModel
class MovieViewModel @Inject constructor(private val repository: MovieRepository) : ViewModel() {

    var response: List<MoviesItem> by mutableStateOf(listOf())
    val errorMessage: String by mutableStateOf("")
    val isLoading = mutableStateOf(false)

    fun getMovies() = viewModelScope.launch {
      val result = repository.getMovieLists()

    }
}

【问题讨论】:

  • 你不需要providesPokemonRepository函数。您的存储库已经进行了构造函数注入,因此 Hilt 将能够创建其实例。只需将MovieRepository 标记为@Singleton。顺便说一句,您的代码中有任何错误吗?你到底在寻求什么帮助?
  • 我想配置视图模型以便我可以使用它,但我不明白我该怎么做@ArpitShukla
  • 您的 ViewModel 对我来说似乎已配置。它有权访问存储库。你还想要什么配置?

标签: kotlin mvvm retrofit android-jetpack-compose dagger-hilt


【解决方案1】:

我猜response 应该需要 UI 中的数据。如果你猜错了,请忽略这个答案。否则,响应应该是 Ui as State。

您已将 List&lt;MoviesItem&gt; 作为状态提升到 ViewModel。数据都在 ViewModel 中,因此数据的访问和更新都发生在 ViewModel 中。

如果getMovies()是一个更新数据的函数,那么只需将结果放入response即可。

Response 是 Ui 的状态,你用 MutableState 来包装它。

var response by mutableStateOf(listOf<MoviesItem>())
    private set
 
fun getMovies() = viewModelScope.launch {
     response = repository.getMovieLists()
}

在撰写功能中,您可以通过viewModel.response 访问您的最新状态。

您还可以查看 ViewModel 上的 Android Compose 文档

https://developer.android.com/jetpack/compose/state#viewmodel-state

【讨论】:

    猜你喜欢
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    • 2011-04-13
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多