---
# System prepended metadata

title: 2020-04-21 | Kotlin | API request & Coroutines
tags: [android, kotlin, gobelins, api, thread]

---

# 2020-04-21 | Kotlin | API request & Coroutines

###### tags: `kotlin` `android` `gobelins` `api` `thread`

## Permissions (Manifest.xml)
```xml
<uses-permission android:name="android.permission.INTERNET"/>
```

## Dependencies (build.graddle)
```
    // API
    implementation "com.squareup.retrofit2:retrofit:2.6.0"
    implementation "com.squareup.okhttp3:okhttp:3.12.2"
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

    // COROUTINES
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.0"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutinesandroid:1.1.1"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.3.0-alpha01"
```

## API
[News Api](https://newsapi.org/)

## Classes
```kotlin
data class ArticleResult (
    val status: String,
    val totalResults:String,
    val articles: List<Article>
)

data class Article(
    val source:Source,
    val author:String,
    val title:String,
    val description:String,
    val url:String,
    val urlToImage:String,
    val publishedAt:String,
    val content:String
)

data class Source (
    val id:String,
    val name:String
)
```

## Service
```kotlin
interface ArticleService {
    @GET("/top-headlines")
    fun list(): Call<ArticleResult>
}
```

## Repository
```kotlin
class Articlepository {
    private val service: ArticleService

    init {
        // Instance retrofit avec url commune de l'api
        val retrofit = Retrofit.Builder().apply {
            baseUrl("https://newsapi.org/v2")
        }.build()

        // Instance du service
        service = retrofit.create(ArticleService::class.java)
    }

    fun list(): List<Article> {
        val response = service.list().execute()

        // Le body peut être nul, alors on anticipe
        return response.body()?.articles ?: emptyList()
    }
}
```

## Fragments 
```kotlin
class ListArticleFragment : Fragment() {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        //Sur le thread principal
        lifecycleScope.launch {
            //Faire quelque ici
        }

        //Dans un thread secondaire
        lifecycleScope.launch(Dispatchers.IO) {
            //Faire quelque ici
        }
    }
}
```


