Android 挂起函数通用形式
我在我的存储库中使用挂起函数,每个函数都有try-catch块,代码是重复的 例如:Android 挂起函数通用形式,android,kotlin,Android,Kotlin,我在我的存储库中使用挂起函数,每个函数都有try-catch块,代码是重复的 例如: class ApiRepository(private val api: Api) { suspend fun listAllProducts(): Response<List<Product>> { return try { val response = api.listAllProducts() Respons
class ApiRepository(private val api: Api) {
suspend fun listAllProducts(): Response<List<Product>> {
return try {
val response = api.listAllProducts()
Response.Success(Mapper.toProductList(response))
} catch (e: Exception) {
e.printStackTrace()
Response.Error(e)
}
}
suspend fun listAllProductCategories(): Response<List<Category>> {
return try {
val response = api.listAllProductCategories()
Response.Success(Mapper.toCategoryList(response))
} catch (e: Exception) {
e.printStackTrace()
Response.Error(e)
}
}
}
class api存储库(私有val api:api){
挂起趣味listAllProducts():响应{
回击{
val response=api.listAllProducts()
Response.Success(Mapper.toProductList(Response))
}捕获(e:例外){
e、 printStackTrace()
答复.错误(e)
}
}
suspend fun listAllProductCategories():响应{
回击{
val response=api.listAllProductCategories()
Response.Success(Mapper.toCategoryList(Response))
}捕获(e:例外){
e、 printStackTrace()
答复.错误(e)
}
}
}
响应类
sealed class Response<T> {
data class Success<T>(val value: T) : Response<T>()
data class Error<T>(val t: Throwable) : Response<T>()
}
密封类响应{
数据类成功(val值:T):响应()
数据类错误(val t:Throwable):响应()
}
有更通用的方法吗?可以使用这样的高阶函数:
inline fun <T> getResponse(block: ()->T): Response<T> {
return try {
Response.Success(block())
} catch (e: Exception) {
e.printStackTrace()
Response.Error(e)
}
}
inline fun getResponse(块:()->T):响应{
回击{
Response.Success(block())
}捕获(e:例外){
e、 printStackTrace()
答复.错误(e)
}
}
然后像这样使用它:
class ApiRepository(private val api: Api) {
suspend fun listAllProducts(): Response<List<Product>> = getResponse {
Mapper.toProductList(api.listAllProducts())
}
suspend fun listAllProductCategories(): Response<List<Category>> = getResponse {
Mapper.toCategoryList(api.listAllProductCategories())
}
}
class api存储库(私有val api:api){
suspend fun listAllProducts():Response=getResponse{
Mapper.toProductList(api.listAllProducts())
}
suspend fun listAllProductCategories():Response=getResponse{
Mapper.toCategoryList(api.listAllProductCategories())
}
}
如果getResponse
是内联的,那么函数是否为挂起函数并不重要