Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // PostRepository.kt
- class PostRepository(private val typicodeService: TypicodeService) {
- fun getPosts(liveData: MutableLiveData<Result>, stateLiveData: MutableLiveData<UIState>) {
- stateLiveData.postValue(UIState.Loading)
- typicodeService.getPosts().enqueue(object : Callback<List<Post>> {
- override fun onResponse(call: Call<List<Post>>, response: Response<List<Post>>) {
- liveData.postValue(Result.Success(response.body()!!))
- stateLiveData.postValue(UIState.Complete)
- }
- override fun onFailure(call: Call<List<Post>>, t: Throwable) {
- liveData.postValue(Result.Failure())
- stateLiveData.postValue(UIState.Complete)
- }
- })
- }
- }
- // MainViewModel.kt
- class MainViewModel : ViewModel() {
- private val postRepository = PostRepository(RetrofitFactory.typicodeService)
- private val postLiveData = MutableLiveData<Result>()
- private val stateLiveData = MutableLiveData(UIState.Complete)
- val posts: LiveData<Result> = postLiveData
- val uiState: LiveData<UIState> = stateLiveData
- fun loadPosts() {
- postRepository.getPosts(postLiveData, stateLiveData)
- }
- }
Add Comment
Please, Sign In to add comment