// retrofit 생성
object ContentClient {
private const val BASE_URL = "https://dapi.kakao.com/"
private val retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
val imageApi by lazy {
retrofit.create(ImageApi::class.java)
}
val videoApi by lazy {
retrofit.create(VideoApi::class.java)
}
}
// API Interface
interface ImageApi {
@GET("v2/search/image")
suspend fun searchImage(
@Header("Authorization") apiKey: String = KakaoAuth.AUTH_HEADER,
@Query("query") query: String,
@Query("sort") sort: String,
@Query("page") page: Int,
@Query("size") size: Int
): retrofit2.Response<ImageSearchResponse>
}
// body에 넘어오는 응답정보
data class ImageSearchResponse(
@SerializedName("meta")
val metaData: MetaData?,
@SerializedName("documents")
var documents: MutableList<ImageData>?
)
// kakao에서 건네준 MetaData정보
data class MetaData(
@SerializedName("pageable_count")
val pageableCount: Int?,
@SerializedName("total_count")
val totalCount: Int?,
@SerializedName("is_end")
val isEnd: Boolean?
)
// document에서 받을 실제 데이터(이것보다 훨씬 더 많이 넘어오지만 필요한것만 받음.
data class ImageData(
val id: Long,
@SerializedName("datetime")
val dateTime: String,
@SerializedName("thumbnail_url")
val thumbnail: String
)
viewModelScope.launch {
val list: MutableList<ContentData> = mutableListOf()
val imageRes= repository.searchImage(query, "recency")
val videoRes= repository.searchVideo(query, "recency")
if(imageRes.isSuccessful && videoRes.isSuccessful) {
imageRes.body()?.documents?.let {imageList ->
contentList.value = list
}
}
}
retrofit을 쓰면서 느낀 가장 큰 장점은 interface와 데이터가 1:1 매칭된다는 것이다. 서버스펙이 바뀌어도 쉽게 대응할 수 있을 것 같다.