史上最精简的【带有二级缓存】的【网络请求】封装,Kotlin语言实现,Retrofit2 结合OkHttp3网络层

Overview

MyRetrofitGo

一、史上最精简的【带有二级缓存】的【网络请求】封装,Kotlin语言实现,Retrofit2 结合OkHttp3网络层,ViewModel技术,使用Kotlin协程加载网络数据;并对网络层添加2级缓存功能——内存缓存和文件缓存;同时针对ApiService接口通过注解的形式来配置是否显示loadingDiaog、是否启用缓存功能;开发者可长按Activity后随时查看当前页面的所有网络请求LOG信息,减轻开发工作,且增加用户体验,堪称史上最简洁的代码,实现你想要的功能;

二、缓存逻辑:【开发者无需关心内部实现】

1、无缓存:  调用接口->无内存缓存->无文件缓存-> 加载网络数据->网络数据更新UI->更新网络数据到内存和文件缓存
2、有文件缓存:调用接口 -> 无内存缓存 ->有文件缓存  ->更新到内存缓存 -> 缓存数据更新UI-> 加载网络数据 -> 网络数据更新UI-> 更新网络数据到内存和文件缓存
3、有内存缓存: 调用接口-> 有内存缓存-> 缓存数据更新UI-> 加载网络数据 -> 网络数据更新UI -> 更新网络数据到内存和文件缓存

三、接口声明:

* 如果接口返回数据类型为数组:则返回Datas */ interface InterfaceApi { @MyRetrofitGo(tag = "获取提醒",loading = true, cache = true, hasCacheLoading = false) @POST("home/remind") fun getData( @Query("username") username: String, @Query("age") age: String, ): Data @MyRetrofitGo(loading = false, cache = false) @GET("home/getUser") fun getDatas( @Query("username") username: String, @Query("age") age: String, ): Datas } ">
/**
 * 说明:接口返回类型必须为:Call>,可以简写为Data或者Datas
 *@MyRetrofitGo注解说明:
 *  tag:给接口定义个名字:方便http view查看,默认显示 @POST("home/remind")里的url
 *  loading:是否显示loadingDialog,默认true
 *  cache:是否启用缓存功能,默认true
 *  hasCacheLoading:存在缓存数据时,是否显示loading,默认false
 *@接口方法返回说明【BeanRemind为定义的数据模型】:
 *  如果接口返回数据类型为对象:则返回Data
 *  如果接口返回数据类型为数组:则返回Datas
 */
interface InterfaceApi {

     @MyRetrofitGo(tag = "获取提醒",loading = true, cache = true, hasCacheLoading = false)
     @POST("home/remind")
     fun getData(
         @Query("username") username: String,
         @Query("age") age: String,
     ): Data
 
     @MyRetrofitGo(loading = false, cache = false)
     @GET("home/getUser")
     fun getDatas(
         @Query("username") username: String,
         @Query("age") age: String,
     ): Datas

}

四、ViewModel定义

 /**
 * 继承BaseViewModel,接口调用固定写法:fun youFunction(参数...) = go { APIService接口调用 }
 */
class TestViewModel : BaseViewModel() {

    fun test(name: String) = go { API.getData(name, "23") }

    fun tests(name: String) = go { API.getDatas(name, "23") }
 
}

五、Activity中调用:

        var vm = initVM(TestViewModel::class.java)

        //获取Object数据
        vm.test(this, "name1").obs(this) {
            it.c { "缓存数据${it.toJson()}".log() } 
            it.y { "网络数据${it.toJson()}".log() } 
            it.n { "异常数据${it.toJson()}".log() } 
        }

        //获取Array数据
        vm.tests(this, "name2").obs(this) {
            it.c { "缓存数据${it.toJson()}".log() } 
            it.y { "网络数据${it.toJson()}".log() } 
            it.n { "异常数据${it.toJson()}".log() } 
        }
        

六、数据回调方法说明:【 c:cache简写;y:yes简写;n:no简写;调用顺序可随意】

it.c {  } : 缓存数据加载成功回调;如果不使用缓存,可delete该行代码;如果数据分页,当page==1时,才使用缓存数据;
it.y {  } : 网络数据加载成功回调;如果不处理成功,可delete该行代码;如果数据分页,当page==1时,清空list里缓存数据,再添加网络数据到list;
it.n {  } : 网络数据加载失败回调;如果不处理失败,可delete该行代码;如果数据加载失败,且缓存数据存在,根据需要写失败逻辑;

以上代码只是以下代码的简写【省略了else,只为让代码看起来更优雅,更性感,3个If块只会同时执行一个】:

if(it.errno==0&&it.cache){
    //缓存
}
if(it.errno==0&&!it.cache){
    //成功
}
if(it.errno!=0&&!it.cache){
    //失败
}

七、效果

Video_20210626_034427_427 Video_20210627_121527_755

八、随时查看http请求Log【Activity长按1秒,可查看当前Activity的所有网络请求log】

Video_20210702_092144_23

请资助我一个棒棒糖吧,在此感谢:

微信图片_20210609173434

You might also like...
Showify is a my first simple ✅ Android application 📱 using DI, where I learn how to use dagger-hilt, retrofit2, mvvm, livedata, Requestly Interceptor
Showify is a my first simple ✅ Android application 📱 using DI, where I learn how to use dagger-hilt, retrofit2, mvvm, livedata, Requestly Interceptor

Showify is a my first simple ✅ Android application 📱 using DI, where I learn how to use dagger-hilt, retrofit2, mvvm, livedata, Requestly Interceptor and so much more...

A Clean Architecture App that uses clean Architecture (app, presentation, domain, data) packages to use coffee items API using MVVM Architecture, Coroutines, Retrofit2, Pagination, Live Data, Data Binding, Hilt , SOLID Principles , Navigation Component , RoomDb. Kotlin, MVVM, Navigation Component, Hilt, Jetpack Compose, Coroutine, MutableState, Retrofit2, Glide
Kotlin, MVVM, Navigation Component, Hilt, Jetpack Compose, Coroutine, MutableState, Retrofit2, Glide

MVVM-RecipeApp Kotlin, MVVM, Navigation Component, Hilt, Jetpack Compose, Coroutine, MutableState, Retrofit2, Glide Main Features Kotlin MVVM Jetpack

Android Kotlin+ MVVM + Retrofit2 + Room +Dagger2 + Coroutines + Junit4 + Espresso + Mockito + MockWebServer

Movies-TMDB Android Kotlin+ MVVM + Retrofit2 + Room +Dagger2 + Coroutines + Junit4 + + Espresso + Mockito + MockWebServer Movies-TMDB Android Movies-T

Owner
陈亮
陈亮
The JeTrivia is built on a modern Android Development tech stack with MVVM architecture. Kotlin, Coroutine, Flow, StateFlow, Jetpack Compose, Navigation, Room, Hilt, Retrofit2, OkHttp3, kotlinx.serialization, MockK, Truth

JeTrivia ?? In Progress ?? The JeTrivia application is sample based on MVVM architecture. Fetching data from the network via repository pattern and sa

Tolga Bolatcan 5 Mar 31, 2022
An simple image gallery app utilizing Unsplash API to showcase modern Android development architecture (MVVM + Kotlin + Retrofit2 + Hilt + Coroutines + Kotlin Flow + mockK + Espresso + Junit)

Imagine App An simple image gallery app utilizing Unsplash API. Built with ❤︎ by Wajahat Karim and contributors Features Popular photos with paginatio

Wajahat Karim 313 Jan 4, 2023
A simple Android Application with MVVM Architecture, Coroutine, Retrofit2

Retrofit with Coroutines and MVVM Architecture. A simple Android Application with MVVM Architecture Developed Using LiveData. MVVM Architecture. Retro

Ahmed Eid 0 Oct 12, 2021
simple app used Kotlin MVVM Dagger2 Room Coroutines Retrofit2

Exhibits Application which retrieves data from Webserver (via Retrofit), saves it into Room and get from it if user is offline. There are applying MVV

Ahmed Eid 0 Oct 14, 2021
kotlin mvvm+dataBinding+retrofit2+Arouter等BaseActivity、BaseFragment、BaseDialogFragment基类封装

kotlin-mvvm kotlin mvvm+dataBinding+retrofit2+ARouter等BaseActivity、BaseFragment、BaseDialogFragment基类封装 Android开发项目基本使用框架,封装了各类组件,在基类实现了沉浸式状态栏,可以自己更改颜色

奋斗中的骚年 3 Jul 12, 2022
Kotlin, MVVM, Navigation Component, Hilt, Jetpack Compose, Retrofit2

What is this project? This course will replace my old java mvvm introduction: https://codingwithmitch.com/courses/rest-api-mvvm-retrofit2/. Watch the

Mitch Tabian 452 Jan 1, 2023
An app which displays questions from Stack Exchange from it's api. Can search questions with tags as well. Uses MVVM architecture, dependency injection, coroutines, retrofit2 for network calls

Stack Exchange app What the app does? Shows a list of trending questions from stack exchange api Can search for the desires question. Can add tags to

null 0 Apr 27, 2022
(Coroutine, Flow(+StateFlow), Hilt, JetPack, MVVM, Repository Pattern, Retrofit2 & OkHttp3, Moshi, Glide, Timber, Material-Components)

(Coroutine, Flow(+StateFlow), Hilt, JetPack, MVVM, Repository Pattern, Retrofit2 & OkHttp3, Moshi, Glide, Timber, Material-Components)

훈성 2 Nov 15, 2022
Jetpack Compose, Kotlin, MVVM, Navigation Component, Hilt, Retrofit2

Jetpack-Compose-Blueprint Jetpack Compose, Kotlin, MVVM, Navigation Component, Hilt, Retrofit2 Apps Packages data : It contains all the data accessing

Jai Khambhayta 14 Dec 15, 2022
BooksApp - Show the books list from an API with using retrofit2, picasso and JSON libraries

BooksApp Books App Show the books list from an API with using retrofit2, picasso

null 0 Jan 3, 2022