Retrofit
Dependencies
Section titled “Dependencies”implementation("com.squareup.retrofit2:retrofit:2.11.0")implementation("com.squareup.retrofit2:converter-gson:2.9.0")Example data class
Section titled “Example data class”data class Music( val title: String, val url: String)Create interface for API actions
Section titled “Create interface for API actions”interface Api { @GET("/music") suspend fun getMusic(): List<Music>}Create Retrofit Instance
Section titled “Create Retrofit Instance”object RetrofitInstance { val api: Api by lazy { Retrofit.Builder() .baseUrl("https://skills-music-api.eliaschen.dev") // Example host .addConverterFactory(GsonConverterFactory.create()) .build() .create(Api::class.java) }}ViewModel to retrieve data
Section titled “ViewModel to retrieve data”class MainViewModel : ViewModel() { private val _musicList = MutableStateFlow<List<Music>>(emptyList()) val musicList: StateFlow<List<Music>> get() = _musicList // handle error private val _failed = MutableStateFlow(false) val failed: StateFlow<Boolean> get() = _failed
init { fetchMusicList() }
private fun fetchMusicList() { viewModelScope.launch { try { val musicList = RetrofitInstance.api.getMusic() _musicList.value = musicList } catch (e: Exception) { _failed.value = true } } }}Retrieve data in composable
Section titled “Retrieve data in composable”@Composablefun MusicListScreen(viewModel: MainViewModel = viewModel()) { val musicList by viewModel.musicList.collectAsState() val failed by viewModel.failed.collectAsState() if (!failed) { LazyColumn { items(musicList) { music -> Column { Text(text = music.title) Text(text = music.url) } } } } else { Text("Failed Request!!!") }}