Advertisement
EugeneKotlin

retrofit

Mar 27th, 2021
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.76 KB | None | 0 0
  1. interface UsersApi {
  2.     @GET("users" + "&format=json")
  3.     fun fetchContents(): Call<MyResponse>
  4. }
  5.  
  6. class UserFetchr {
  7.  
  8.     private val usersApi: UsersApi
  9.  
  10.     init {
  11.         val retrofit: Retrofit = Retrofit.Builder()
  12.             .baseUrl("https://reqres.in/api/")
  13.             .addConverterFactory(GsonConverterFactory.create())
  14.             .build()
  15.  
  16.         usersApi = retrofit.create(UsersApi::class.java)
  17.     }
  18.  
  19.     fun fetchContents(): LiveData<List<UserItem>> {
  20.  
  21.         val responseLiveData: MutableLiveData<List<UserItem>> = MutableLiveData()
  22.         val usersRequest: Call<MyResponse> = usersApi.fetchContents()
  23.  
  24.         usersRequest.enqueue(object : Callback<MyResponse> {
  25.  
  26.             override fun onFailure(call: Call<MyResponse>, t: Throwable) {
  27.                 Log.e(TAG, "Failde to fetch users", t)
  28.                 t.printStackTrace()
  29.             }
  30.  
  31.             override fun onResponse(call: Call<MyResponse>,
  32.                                     response: Response<MyResponse>) {
  33.  
  34.                 val myResponse: MyResponse? = response.body()
  35.                 val userResponse: UserResponse? = myResponse?.users
  36.                 val userItems: List<UserItem> = userResponse?.userItems
  37.                     ?: mutableListOf()
  38.                 responseLiveData.value = userItems
  39.             }
  40.         })
  41.         return responseLiveData
  42.     }
  43. }
  44.  
  45. class MyResponse(var users: UserResponse)
  46.  
  47. class UserResponse(@SerializedName("data") var userItems: List<UserItem>)
  48.  
  49. data class UserItem(
  50.     @SerializedName("id") var id: Int,
  51.     @SerializedName("avatar") var urlImage: String,
  52.     @SerializedName("first_name") var firstName: String,
  53.     @SerializedName("last_name") var lastName: String,
  54.     @SerializedName("email") var email: String
  55. ){}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement