Jetpack Retrofit
JlozorikModules:
implementation ("com.squareup.retrofit2:retrofit:2.9.0") // retrofit implementation ("com.squareup.retrofit2:converter-gson:2.9.0") implementation ("io.coil-kt:coil-compose:2.0.0-rc01") // async images implementation ("com.squareup.okhttp3:okhttp:4.7.2") // logging implementation ("com.squareup.okhttp3:logging-interceptor:4.7.2")
DataClass:
data class Episodes( @SerializedName("@id") val musor : Any? = null // для незаконных id val released: Boolean = false, val total: Any? = null )
Interface:
interface ImageApi { @GET("search") // Только то,что нужно, основной адрес ниже suspend fun getEpisodes( @Query("included_tags") tag : String, @Query("many") many : Boolean, @Header("asa") asa : String = "a") : Episodes //DataClass //creating Retrofit companion object { var apiService : ImageApi? = null fun getInstance() : ImageApi { if (apiService == null){ // LOgging val interceptor = HttpLoggingInterceptor() interceptor.level = HttpLoggingInterceptor.Level.BODY val client = OkHttpClient.Builder().addInterceptor(interceptor).build() //MainService apiService = Retrofit.Builder() .baseUrl("https/example.ru/") //baseUrl with "/" .client(client) .addConverterFactory(GsonConverterFactory.create()) .build().create(ImageApi::class.java) } return apiService!! } } }
ViewModel:
class SimpleVM : ViewModel() { var episodes : Episodes by mutableStateOf(Episodes()) // DataClass private val _uiState = MutableStateFlow(UIState()) //UiState val uiState: StateFlow<UIState> = _uiState init{ getEpisodes() } fun getEpisodes(){ viewModelScope.launch { val service = ImageApi.getInstance() try { val response = service.getEpisodes() // params if any anime = response // be careful with contentType!!! } catch (e: Exception){ // try/catch println(e.localizedMessage) } } }