Android Compose 新闻App(一)网络框架搭建

.build()

fun create(serviceClass: Class): T = getRetrofit().create(serviceClass)

inline fun create(): T = create(T::class.java)

}

这里的代码就很简单了,通过网络地址构建一个Retrofit,然后根据传入的Service去访问接口,这里还有一个内联函数。

下面我们来构建这个服务接口,在此之前先在com.llw.goodnews包下新建一个utils包,包下新建一个Constant的类,里面的代码如下:

object Constant {

/**

  • 天行数据Key,请使用自己的Key

*/

const val API_KEY = “d8bc937c366fcd1629e00f19105db258”

/**

  • 请求接口成功状态码

*/

const val CODE = 200

/**

  • 请求接口成功状态描述

*/

const val SUCCESS = “success”

}

这里就是一个常量类,我们在请求API接口时会用到的一些不变的值就放这里。然后我们在network包下新建一个ApiService接口,代码如下:

interface ApiService {

/**

  • 获取新闻数据

*/

@GET(“/ncov/index?key=$API_KEY”)

fun getEpidemicNews(): Call

}

下面我们在network包下新建一个发起请求的NetworkRequest类,代码如下:

object NetworkRequest {

/**

  • 创建服务

*/

private val service = ServiceCreator.create(ApiService::class.java)

//通过await()函数将getNews()函数也声明成挂起函数。使用协程

suspend fun getEpidemicNews() = service.getEpidemicNews().await()

/**

  • Retrofit网络返回处理

*/

private suspend fun Call.await(): T = suspendCoroutine {

enqueue(object : Callback {

//正常返回

override fun onResponse(call: Call, response: Response) {

val body = response.body()

if (body != null) it.resume(body)

else it.resumeWithException(RuntimeException(“response body is null”))

}

//异常返回

override fun onFailure(call: Call, t: Throwable) {

it.resumeWithException(t)

}

})

}

}

这段代码解释一下:首先我们使用ServiceCreator创建了一个ApiService接口的动态代理对象,然后定义了一个getEpidemicNews函数,调用刚刚在ApiService中定义的getEpidem

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值