// Retrofit
implementation("com.squareup.retrofit2:retrofit:2.9.0")
// Retrofit with Scalar Converter
implementation("com.squareup.retrofit2:converter-scalars:2.9.0")
private const val BASE_URL =
"https://android-kotlin-fun-mars-server.appspot.com"
private val retrofit = Retrofit.Builder()
.addConverterFactory(ScalarsConverterFactory.create())
.baseUrl(BASE_URL)
.build()
import retrofit2.http.GET
interface MarsApiService {
@GET("photos")
fun getPhotos(): String
}
object 선언
예제
// Example for Object declaration, do not copy over
object SampleDataProvider {
fun register(provider: SampleProvider) {
// ...
}
// ...
}
// To refer to the object, use its name directly.
SampleDataProvider.register(...)
object MarsApi {
val retrofitService : MarsApiService by lazy {
retrofit.create(MarsApiService::class.java)
}
}
특징
필요성
활용하기
private fun getMarsPhotos() {
viewModelScope.launch {
val listResult = MarsApi.retrofitService.getPhotos()
marsUiState = listResult // 서버에서 받아온 결과를 UiState에 저장한다.
}
}
권한의 필요성
권한의 작동
인터넷 권한 사용하기
<uses-permission android:name="android.permission.INTERNET" />
exceptions
예외의 해결
try {
// some code that can cause an exception.
}
catch (e: SomeException) {
// handle the exception to avoid abrupt termination.
}
// 위의 네트워크 연결과 같은 경우 다음과 같이 대응한다.
viewModelScope.launch {
try {
val listResult = MarsApi.retrofitService.getPhotos()
marsUiState = listResult
} catch (e: IOException) {
}
}
sealed interface MarsUiState {
data class Success(val photos: String): MarsUiState
object Error : MarsUiState
object Loading : MarsUiState
}
var marsUiState: MarsUiState by mutableStateOf(MarsUiState.Loading)
private set
val listResult = MarsApi.retrofitService.getPhotos()
marsUiState = MarsUiState.Success(listResult)
catch (e: IOException) {
marsUiState = MarsUiState.Error
}
fun HomeScreen(
marsUiState: MarsUiState,
modifier: Modifier = Modifier
) {
when (marsUiState) {
is MarsUiState.Loading -> LoadingScreen(modifier = modifier.fillMaxSize())
is MarsUiState.Success -> ResultScreen(
marsUiState.photos, modifier = modifier.fillMaxWidth()
)
is MarsUiState.Error -> ErrorScreen( modifier = modifier.fillMaxSize() )
}
}
Json 이란?
deserialization
serialization
kotlinx.serialization 라이브러리 사용하기
id("org.jetbrains.kotlin.plugin.serialization") version "1.8.10"
// Kotlin serialization
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.1")
@Serializable
data class MarsPhoto(
val id: String, val img_src: String
)
데이터 클래스를 만드는 이유?
데이터 클래스의 생성
@SerialName(value = "img_src")
val imgSrc: String
private val retrofit = Retrofit.Builder()
.addConverterFactory(Json.asConverterFactory("application/json".toMediaType()))
.baseUrl(BASE_URL)
.build()