Network Requests with Retrofit in Android

Jun 5 2024 · Kotlin 1.9.22, Android 14, Android Studio Hedgehog | 2023.1.1

Lesson 05: Use Retrofit With Coroutines

Demo

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Start by adding suspend and changing the return types of all methods in MovieDiaryApiService. kt like this:

@POST("user/register")
suspend fun registerUser(@Body body: RegisterBody): Response<Unit>

@POST("user/login")
suspend fun loginUser(@Body registerBody: RegisterBody): LoginResponse

@GET("sampleMovies")
suspend fun getMovies(): List<MovieReview>

@GET("user")
suspend fun getProfile(): User

@POST("movies")
suspend fun postReview(@Body movieReview: MovieReview): MovieReview
suspend fun registerUser(
  username: String,
  email: String,
  password: String,
): Result<String> {

}
suspend fun registerUser(
  username: String,
  email: String,
  password: String,
): Result<String> = try {
  val body = RegisterBody(username, email, password)
  val result = apiService.registerUser(body)
  if (result.isSuccessful) {
    Result.success(result.message())
  } else {
    Result.failure(Throwable(result.errorBody()?.string()))
  }
} catch (error: Throwable) {
  Result.failure(error)
}
suspend fun loginUser(
  username: String,
  password: String,
): Result<LoginResponse> {
  return runCatching { apiService.loginUser(RegisterBody(username = username,password = password))}
}
suspend fun getMovies(): Result<List<MovieReview>> = runCatching { apiService.getMovies() }
movieDiaryApi.registerUser(username, email, password)
  .onSuccess {
    Toast.makeText(context, it, Toast.LENGTH_SHORT).show()
    onUserRegistered()
  }.onFailure { scaffoldState.snackbarHostState.showSnackbar(it.message ?: "") }
movieDiaryApi.loginUser(username, password)
  .onSuccess(onLogin)
  .onFailure { scaffoldState.snackbarHostState.showSnackbar(it.message ?: "") }
LaunchedEffect(Unit) {
  movieDiaryApi.getMovies()
    .onSuccess { movieReviewList = it }
    .onFailure { scaffoldState.snackbarHostState.showSnackbar(it.message ?: "") }
}
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion