栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Android整合搭建RxJava+Retrofit+LiveData+OkHttp框架实现MVVM模式开发(学习中)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android整合搭建RxJava+Retrofit+LiveData+OkHttp框架实现MVVM模式开发(学习中)

class LiveDataRetrofitActivity:AppCompatActivity() {
    private lateinit var viewModel: LoginViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_livedata)
        viewModel=  ViewModelProvider(this).get(LoginViewModel::class.java)

    }

    fun login(view: View) {
        viewModel.login(LoginVo("123456","admin"))
            .observe(this,
                Observer> { t ->
                    t?.let {loginDtobaseDto->
                        if (loginDtobaseDto.meta?.status == 200){
                            SPUtil.setString(Constant.TOKEN,loginDtobaseDto.data?.token.toString())
                            Log.e("AAA",loginDtobaseDto.data?.token.toString())
                        }else{
                            Log.e("AAA",loginDtobaseDto.meta?.message.toString())
                        }
                    }
                })
    }

    fun deleteRoute(view: View) {
        viewModel.deleteRoute("16cb1536859f46c6960551ad83b293c2")
            .observe(this,
                Observer> { t ->
                   Log.e("DELETE:",Gson().toJson(t))
                })
    }

}
class LoginViewModel:ViewModel() {
    fun login(loginVo: LoginVo):LiveData>{
        return LoginRepository().login(loginVo)
    }

    fun deleteRoute(id:String):LiveData>{
        return LoginRepository().deleteRoute(id)
    }

    fun sysUserPaging(pageNum: Int, pageSize: Int): LiveData>{
        return LoginRepository().sysUserPaging(pageNum,pageSize)
    }


}
class LoginRepository : baseRepository(), ILoginRepository, IRouteRepository, ISysUserRepository {
    override fun login(loginVo: LoginVo): LiveData> {
        return request(
            RequestRetrofit.getInstance(ApiService::class.java).login(loginVo)
        ).data
    }

    override fun deleteRoute(id: String): LiveData> {
        return request(
            RequestRetrofit.getInstance(ApiService::class.java).patrolRouteDeleteId(id)
        ).data
    }

    override fun sysUserPaging(pageNum: Int, pageSize: Int): LiveData> {
        return request(
            RequestRetrofit.getInstance(ApiService::class.java).sysUserPaging(pageNum, pageSize)
        ).data
    }

}
object RequestRetrofit {
    
    private var okHttpClient: OkHttpClient? = null

    private var retrofit: Retrofit? = null

    fun  getInstance(service: Class): T {
        if (okHttpClient == null) {
            synchronized(RequestRetrofit::class.java) {
                if (okHttpClient == null) {
                    okHttpClient = OkHttpClient.Builder()
                        .addInterceptor(
                            HttpLoggingInterceptor {
                                //访问网络请求,和服务端响应请求时。将数据拦截并输出
                                if ("401" in it) SPUtil.remove(Constant.TOKEN)
                                Log.e("HTTP", it)
                            }.setLevel(HttpLoggingInterceptor.Level.BODY)
                        )
                        .connectTimeout(20, TimeUnit.SECONDS)
                        .readTimeout(20, TimeUnit.SECONDS)
                        .writeTimeout(20, TimeUnit.SECONDS)
                        .addNetworkInterceptor(StethoInterceptor())
                        .addInterceptor(AddcookiesInterceptor())
//                        .addInterceptor(ReceivedcookiesInterceptor())
                        .build()
                }
            }
        }


        if (retrofit == null) {
            synchronized(RequestRetrofit::class.java) {
                if (retrofit == null) {
                    retrofit = Retrofit.Builder()
                        .baseUrl(ApiConfig.baseUrl)
                        .client(okHttpClient!!)
                        .addConverterFactory(GsonConverterFactory.create())
                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .addCallAdapterFactory(CoroutineCallAdapterFactory())
                        .build()
                }
            }
        }

        return retrofit!!.create(service)
    }

}
class baseDto : Serializable{
    var meta: metaData?=null
    var data: T?=null
}

data class metaData(
    var message: String?,
    var status: Int,
    var success: Boolean
)
open class baseRepository {

    
    fun  request(flowable: Flowable>): baseHttpSubscriber {
        val baseHttpSubscriber = baseHttpSubscriber() //RxJava Subscriber回调
        flowable.subscribeOn(Schedulers.io()) //解决背压
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(baseHttpSubscriber)

        return baseHttpSubscriber
    }
}
class PageKeyedSource : PagingSource() {
    override fun getRefreshKey(state: PagingState): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            state.closestPageToPosition(anchorPosition)?.prevKey
        }
    }

    override suspend fun load(params: LoadParams): LoadResult {
        return try {
            //页码未定义置为1
            val currentPage = params.key ?: 1

            val data = RequestRetrofit.getInstance(ApiService::class.java).sysUserPaging2(
                currentPage,
                20
            ).data

            val nextPage = if (currentPage < data?.pages?:0){
                currentPage + 1
            }else{
                null
            }

            if (data != null) {
                LoadResult.Page(
                    data = data.list,
                    prevKey = null,
                    nextKey = nextPage
                )
            } else {
                LoadResult.Error(throwable = Throwable())
            }
        } catch (e: IOException) {
            LoadResult.Error(e)
        } catch (e: HttpException) {
            LoadResult.Error(e)
        }
    }
}
interface ILoginRepository {

    fun login(loginVo: LoginVo): LiveData>?

}

interface IRouteRepository {

    fun deleteRoute(id: String): LiveData>?

}

interface ISysUserRepository {

    fun sysUserPaging(pageNum: Int, pageSize: Int): LiveData>?

}

代码是19年写的了,发上来留个念。AddcookiesInterceptor里只是一个header注入,根据自己实际情况来
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/771079.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号