앱개발/StudyHub 앱 출시 회고
Retrofit 사용해보기 #1
ugyeong
2024. 12. 30. 18:41
오늘은 Retrofit을 사용해 api 통신을 설정해보겠습니다~
1. 싱글톤 객체로 Retrofit 객체 생성하기
싱글톤은 전역에서 한번만 객체가 생성되어 일관된 설정이 가능하고 코드 중복을 최소화할 수 있어요
package kr.co.gamja.study_hub.data.repository
import ...
object RetrofitManager {
private const val BASE_URL = "https://..."
val gson =GsonBuilder().setLenient().create()
// Retrofit 객체를 구성합니다.
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
// retrofit.create : Retrofit은 인터페이스를 기반으로 동적으로 구현체(Proxy 객체)를 생성.
val api = retrofit.create(Api::class.java) // Api : API classs는 api 요청을 정의하는 인터페이스
}
2. api 요청을 처리하는 인터페이스
package kr.co.gamja.study_hub.data.repository
import ...
interface Api {
// suspend 키워드를 사용하면 비동기적으로 네트워크 요청을 수행하고, 결과를 반환할 때까지 호출을 일시 중단.
@GET("/api/...")
suspend fun study(
@Query("page") page: Int,
@Query("size") size: Int
):Response<ParticipatedStudyRequestDto>
}
// HTTP 응답 데이터를 포함하는 객체
data class ParticipatedStudyRequestDto(
val participateStudyData: ParticipateStudyData,
val totalCount: Int
)
Response는 Retrofit 라이브러리에서 네트워크 요청의 결과를 나타내는 클래스이며, 이 클래스는 HTTP 요청에 대한 응답 정보를 캡슐화하며, 요청의 성공 또는 실패 여부와 서버에서 반환된 데이터를 처리하는 데 사용돼요.
3. 호출 부
fun updateEngagedListSize() {
viewModelScope.launch {
val response = RetrofitManager.api.study(0, 10)
try {
if (response.isSuccessful) {
}
} catch (e: Exception) {
}
}
}
다음엔 jwt를 사용한 코드를 소개할게요!