kotlin笔记(4)

作者: EvanPoison | 来源:发表于2018-06-19 02:16 被阅读32次
    1. MVP重构

       1. 创建presenter
       interface HomePresenter {
          
       }
      
       2. 创建presenter实现类
       /**
        * P层需要持有view层的引用
        * 注意: val homeView: HomeView 前面为什么要加val或者var  ,不加,只能在init中使用,在其他自己写的方法,无法调用
        */
       class HomePresenterImpl(val homeView: HomeView) : HomePresenter {
       }
      
       3. 在activity或者fragment使用
           //惰性加载
           val homePresenter by lazy { HomePresenterImpl(this) }
      
           //使用
           homePresenter.loadDatas()  //先生成抽象方法,然后在Impl类中实现该方法,网络请求成功后,再回调到view层
       完整代码:
       /**
        * P层需要持有view层的引用
        * 注意: val homeView: HomeView 前面为什么要加val或者var  ,不加,只能在init中使用,在其他自己写的方法,无法调用
        */
       class HomePresenterImpl(val homeView: HomeView) : HomePresenter {
           /**
            * 加载home界面数据或者刷新数据
            */
           override fun loadDatas() {
               val path = URLProviderUtils.getHomeUrl(0, 20)
               val request = Request.Builder()
                       .get()
                       .url(path)
                       .build()
               OkHttpClient().newCall(request).enqueue(object : Callback {
                   override fun onFailure(call: Call?, e: IOException?) {
                       ThreadUtil.runOnUiThread(Runnable {
                           homeView.onError(e?.message)
                       })
      
      
      
                   }
      
                   override fun onResponse(call: Call?, response: Response?) {
       //                myToast("请求成功:" + Thread.currentThread().name)
                       val result = response?.body()?.string()
                       LogUtil.json(result, "请求成功:")
      
                       val gson = Gson()
                       val list = gson.fromJson<List<HomeItemBean>>(result, object : TypeToken<List<HomeItemBean>>() {}.type)
      
                       ThreadUtil.runOnUiThread(Runnable {
                           homeView.onLoadSuccess(list)
                       })
      
      
                   }
               })
           }
      
      
           override fun loadMore(offset: Int) {
               val path = URLProviderUtils.getHomeUrl(offset, 20)
               val request = Request.Builder()
                       .get()
                       .url(path)
                       .build()
               OkHttpClient().newCall(request).enqueue(object : Callback {
                   override fun onFailure(call: Call?, e: IOException?) {
      
      
                       ThreadUtil.runOnUiThread(Runnable {
                           homeView.onError(e?.message)
                       })
      
      
      
                   }
      
                   override fun onResponse(call: Call?, response: Response?) {
      
                       val result = response?.body()?.string()
                       LogUtil.json(result, "请求成功:")
      
                       val gson = Gson()
                       val list = gson.fromJson<List<HomeItemBean>>(result, object : TypeToken<List<HomeItemBean>>() {}.type)
      
                       ThreadUtil.runOnUiThread(Runnable {
                           homeView.onLoadMoreSuccess(list)
                       })
      
      
                   }
               })
           }
      
      
       }
      
      
       //回调view层
       override fun onLoadSuccess(list: List<HomeItemBean>?) {
           //
           refreshLayout.isRefreshing = false
           homeAdapter.updateList(list)
       }
      
       override fun onLoadMoreSuccess(list: List<HomeItemBean>?) {
           homeAdapter.loadMore(list)
       }
      
    2. let表达式

       /**
        * 刷新数据
        */
       fun updateList(list: List<HomeItemBean>?) {
      
          list?.let {
              this.list.clear()
              this.list.addAll(list)
              notifyDataSetChanged()
          }
      
           //this.list.clear()
           //this.list.addAll(list!!)
           //notifyDataSetChanged()
      
      
       }
      
    3. 网络框架的封装

       1. 所有请求的基类
       class MRequest<T>(val url:String,val responseHandler: ResponseHandler<T>) {}
      
       2. 请求的回调
       interface ResponseHandler<T> {
           fun onError(msg:String)
           fun onSuccess(result:T)
       }
      
       3. 发送网络请求的类
       /**
        *  发送网络请求的类
        */
       class NetManager private constructor(){
      
           val client by lazy { OkHttpClient() }
      
           companion object {
               val manager by lazy { NetManager() }
           }
      
           fun <T>sendRequest(req:MRequest<T>){
      
               val request = Request.Builder()
                       .get()
                       .url(req.url)
                       .build()
               client.newCall(request).enqueue(object : Callback {
                   override fun onFailure(call: Call?, e: IOException?) {
                       ThreadUtil.runOnUiThread(Runnable {
                           req.responseHandler.onError(e?.message)
                       })
      
      
      
                   }
      
                   override fun onResponse(call: Call?, response: Response?) {
                       //myToast("请求成功:" + Thread.currentThread().name)
                       val result = response?.body()?.string()
                       LogUtil.json(result, "请求成功:")
      
                       //网络请求的解析
                       val parseResult = req.parseResult(result)
      
                       ThreadUtil.runOnUiThread(Runnable {
                           req.responseHandler.onSuccess(parseResult)
                       })
      
      
                   }
               })
           }
       }
      
       //补充 网络请求的解析
       /**
        * 所有请求的基类
        */
       class MRequest<T>(val url:String,val responseHandler: ResponseHandler<T>) {
      
           /**
            * 解析网络请求的结果
            */
           fun parseResult(result: String?): T {
               val gson = Gson()
      
               //获取泛型类型
               val type = (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0]
               val result = gson.fromJson<T>(result, type)
               return result
           }
      
           /**
            * 执行网络请求
            */
           fun excute(){
               //发送request
               NetManager.manager.sendRequest(this)
           }
       }
      
    4. 在P层调用

       override fun loadMore(offset: Int) {
       //定义request
       val request = HomeRequest(offset,object : ResponseHandler<List<HomeItemBean>>{
           override fun onError(msg: String?) {
               homeView.onError(msg)
           }
      
           override fun onSuccess(result: List<HomeItemBean>) {
               homeView.onLoadMoreSuccess(result)
           }
       }).excute()
       
       //发送request
       //NetManager.manager.sendRequest(request)
      

      }

    相关文章

      网友评论

        本文标题:kotlin笔记(4)

        本文链接:https://www.haomeiwen.com/subject/orvoeftx.html