Serverless Kotlin on Google Cloud Run

Learn how to build a serverless API using Ktor then dockerize and deploy it to Google Cloud Run. By Kshitij Chauhan.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

Using the Service Interface

Create LocationService.kt in the location package. Within this file, add a new object LocationService with a private property to hold a reference to the Retrofit service:

import com.yourcompany.android.serverlesskt.api.retrofit
import com.yourcompany.android.serverlesskt.api.LocationApi

object LocationService {
  private val api = retrofit.create(LocationApi::class.java)
}

Finally, add a method to send network requests to the API:

import com.yourcompany.android.serverlesskt.api.LocationResponse

object LocationService {
  private val api = // ...
  
  suspend fun fetchLocation(): Result<LocationResponse> {
    return try {
      val location = api.getLocation()
      Result.success(location)
    } catch (ex: Throwable) {
      Result.failure(ex)
    }
  }
}

Build the application to make sure there aren’t compilation errors.

Integrating with ViewModel

While the LocationService knows how to make network requests to the API, the trigger for the requests resides in the view layer of the application.

Navigate to the LocationViewModel.kt file in the location package. It defines a simple ViewModel that contains a dummy implementation of the network request in fetchLocation.

Modify fetchLocation to call the service instead:

fun fetchLocation() {
  viewModelScope.launch {
    _state.value = LocationState.Loading

    LocationService.fetchLocation()
      .onSuccess { response -> _state.value = LocationState.Success(response) }
      .onFailure { error ->
        _state.value = LocationState.Error(error.message ?: "An unknown error occurred")
      }
  }
}

You’ll need to add the following to the LocationState sealed class:

data class Success(val location: LocationResponse) : LocationState()

Open LocationFragment.kt and handle this state inside onCreateView:

override fun onCreateView(...) {
  // ...
  when (state) {
    // ...
    is LocationState.Success -> renderSuccess(state.location)
  }
}

Finally, add the missing renderSuccess method with the following content:

private fun renderSuccess(location: LocationResponse) = binding.apply {
  progressBar.visibility = View.GONE
  locationInfo.text = buildString {
    appendLine("City: ${location.city}")
    appendLine("Region: ${location.regionName}")
    appendLine("Country: ${location.country}")
  }
}

Don’t forget to include the internet permission in the app’s AndroidManifest.xml file!

<uses-permission android:name="android.permission.INTERNET"/>

Build and run. Press the Locate Me button to send a network request and get your approximate location.


App main screen with location

Where to Go From Here?

Download the completed project files by clicking the Download Materials button at the top or bottom of the tutorial.

Congratulations! You learned a lot in this tutorial and can now build and deploy serverless Kotlin apps on Google Cloud Run.

If you’re wondering what to learn next, check out the official documentation for Google Cloud Run, or this tutorial for building Kotlin APIs on GCP.

We hope you enjoyed this tutorial. If you have any questions or comments, please join the forum discussion below!