Skip to content

Instantly share code, notes, and snippets.

@pranay1494
Last active May 2, 2020 16:34
Show Gist options
  • Save pranay1494/fa6686e7417da8df9391bcc5b30ead28 to your computer and use it in GitHub Desktop.
Save pranay1494/fa6686e7417da8df9391bcc5b30ead28 to your computer and use it in GitHub Desktop.
package com.example.coroutinesdemo.ui
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.coroutinesdemo.api.model.User
import com.example.coroutinesdemo.base.BaseViewModel
import com.example.coroutinesdemo.base.ViewStatus
import com.example.coroutinesdemo.repository.UserRepository
import kotlinx.coroutines.launch
import java.lang.Exception
import javax.inject.Inject
open class UserViewModel @Inject constructor(private val repository: UserRepository) : BaseViewModel() {
private val userData = MutableLiveData<DisplayData>()
fun getData(): LiveData<DisplayData> = userData
fun fetchUserData(username: String) = viewModelScope.launch {
viewStatus.postValue(ViewStatus.LOADING)
try {
val user = repository.fetchRepository("pranay1494")
userData.postValue(getUserDisplayData(user))
} catch (e: Exception) {
handleError(e)
} finally {
viewStatus.postValue(ViewStatus.SUCCESS)
}
}
private fun getUserDisplayData(user: User): DisplayData = DisplayData(name = user.name?:"", avatarUrl = user.avatarUrl?:"")
data class DisplayData(val name :String = "",val avatarUrl:String = "")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment