Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- interface UsersApi {
- @GET("users" + "&format=json")
- fun fetchContents(): Call<MyResponse>
- }
- class UserFetchr {
- private val usersApi: UsersApi
- init {
- val retrofit: Retrofit = Retrofit.Builder()
- .baseUrl("https://reqres.in/api/")
- .addConverterFactory(GsonConverterFactory.create())
- .build()
- usersApi = retrofit.create(UsersApi::class.java)
- }
- fun fetchContents(): LiveData<List<UserItem>> {
- val responseLiveData: MutableLiveData<List<UserItem>> = MutableLiveData()
- val usersRequest: Call<MyResponse> = usersApi.fetchContents()
- usersRequest.enqueue(object : Callback<MyResponse> {
- override fun onFailure(call: Call<MyResponse>, t: Throwable) {
- Log.e(TAG, "Failde to fetch users", t)
- t.printStackTrace()
- }
- override fun onResponse(call: Call<MyResponse>,
- response: Response<MyResponse>) {
- val myResponse: MyResponse? = response.body()
- val userResponse: UserResponse? = myResponse?.users
- val userItems: List<UserItem> = userResponse?.userItems
- ?: mutableListOf()
- responseLiveData.value = userItems
- }
- })
- return responseLiveData
- }
- }
- class MyResponse(var users: UserResponse)
- class UserResponse(@SerializedName("data") var userItems: List<UserItem>)
- data class UserItem(
- @SerializedName("id") var id: Int,
- @SerializedName("avatar") var urlImage: String,
- @SerializedName("first_name") var firstName: String,
- @SerializedName("last_name") var lastName: String,
- @SerializedName("email") var email: String
- ){}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement