Skip to content

Making requests

At the moment all calls are suspended and require to be called in Kotlin Coroutines. An overview of how to use them can be found here: Composing suspending functions.

They’re also wrapped in NetworkResponses, so you can react for errors easily or access the data directly.

Examples

Searching with error handling

There are four cases which the response can take value of: Success, ServerError, NetworkError and UnknownError. For more info you should take a look here.

fun main() = runBlocking {
    TMDb.init("YOUR_API_KEY")

    when (val response = TMDb.searchService.tv("Black Clover")) {
        // Type: NetworkResponse<TmdbPage<TmdbShow.Slim>, TmdbError.DefaultError>
        is NetworkResponse.Success -> {
            val searchPage: TmdbPage<TmdbShow.Slim> = response.body
            if (searchPage.totalResults > 0) {
                println("First result's title: ${searchPage.results[0].title}")
            }
        }
        is NetworkResponse.ServerError -> {
            val errorBody: TmdbErrorResponse = response.body
            println("ServerError: Message = ${errorBody?.message}")
        }
        is NetworkResponse.NetworkError -> {
            val error: IOException = response.error
            println("NetworkError: Message = ${error.message}")
        }
        is NetworkResponse.UnknownError -> {
            val error: Throwable = response.error
            println("UnknownError: Message = ${error.message}")
        }
    }
}

Searching with direct access

You can also access the response directly without checking for the NetworkResponse type by calling invoke(). In this case the object might be null:

fun main() = runBlocking {
    TMDb.init("YOUR_API_KEY")

    val searchPage: TmdbPage<TmdbShow.Slim>? = 
        TMDb.searchService.tv("Black Clover").invoke()

    searchPage?.let {
        if (searchPage.totalResults > 0) {
                println("First result: ${searchPage.results[0].title}")
        }
    }
}