Neowise

MainViewModel.kt

Aug 22nd, 2021 (edited)
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.23 KB | None | 0 0
  1. // PostRepository.kt
  2. class PostRepository(private val typicodeService: TypicodeService) {
  3.  
  4.     fun getPosts(liveData: MutableLiveData<Result>, stateLiveData: MutableLiveData<UIState>) {
  5.  
  6.         stateLiveData.postValue(UIState.Loading)
  7.  
  8.         typicodeService.getPosts().enqueue(object : Callback<List<Post>> {
  9.  
  10.             override fun onResponse(call: Call<List<Post>>, response: Response<List<Post>>) {
  11.                 liveData.postValue(Result.Success(response.body()!!))
  12.                 stateLiveData.postValue(UIState.Complete)
  13.             }
  14.  
  15.             override fun onFailure(call: Call<List<Post>>, t: Throwable) {
  16.                 liveData.postValue(Result.Failure())
  17.                 stateLiveData.postValue(UIState.Complete)
  18.             }
  19.         })
  20.     }
  21. }
  22.  
  23.  
  24.  // MainViewModel.kt
  25. class MainViewModel : ViewModel() {
  26.  
  27.     private val postRepository = PostRepository(RetrofitFactory.typicodeService)
  28.     private val postLiveData = MutableLiveData<Result>()
  29.     private val stateLiveData = MutableLiveData(UIState.Complete)
  30.  
  31.     val posts: LiveData<Result> = postLiveData
  32.     val uiState: LiveData<UIState> = stateLiveData
  33.  
  34.     fun loadPosts() {
  35.         postRepository.getPosts(postLiveData, stateLiveData)
  36.     }
  37. }
Add Comment
Please, Sign In to add comment