zoukankan      html  css  js  c++  java
  • Android Architecture Components

    https://developer.android.com/topic/libraries/architecture/index.html

    ViewModel 有LiveData

    Activity 监听(observe) LiveData, LiveData有变化通知Activity

    1.ViewModel定义

    Since these objects might be destroyed or re-created by the operating system, any data you hold in them will be lost. For instance, if you have a list of users in your activity, when the activity is re-created for a configuration change, the new activity will have to re-fetch the list of users. For simple data, the activity can use the onSaveInstanceState() method and restore its data from the bundle in onCreate(), but this approach is only suitable for small information like UI state, not for potentially large amounts of data like a list of users.
    
    Another problem is that, these UI Controllers (activities, fragments, and so on) frequently need to make some asynchronous calls which may take some time to return. The UI Controller needs to manage these calls and clean them up when it is destroyed to avoid potential memory leaks. This requires a lot of maintenance, and in the case where the object is recreated for a configuration change, it is a waste of resources since it will need to re-issue the same call.
    
    Last but not least, these UI Controllers already have a lot of responsibility to react to user actions or handle the operating system communication. When they also need to handle their resources manually, it bloats the class, creating "god activities" (or "god fragments"); that is, a single class that tries to handle all of an app's work all by itself, instead of delegating work to other classes. This also makes testing a lot harder.
    
    It would be easier and more efficient to separate out view data ownership from UI controller logic. Lifecycles provides a new class called ViewModel, which is a helper class for the UI Controller that is responsible to prepare the data for the UI. The ViewModel is automatically retained during configuration changes so the data it holds is immediately available to the next activity or fragment instance. For the example we’ve mentioned above, it would be the ViewModel’s responsibility to acquire and keep the list of users, not the activity or the fragment.

     LiveData: active inactive.

    后台的时候不会更新UI,回到前台的时候,会把最新的数据更新到ui



    上层不依赖下层的任何东西
    ui controller 依赖view model
    测试ui controller, mock view model
    测试view model, mock repository
    测试repository, mock data source

  • 相关阅读:
    使用 jfinal + beetl + bootstrap 实现商城展示及管理系统
    关于Node.js的__dirname,__filename,process.cwd(),./文件路径的一些坑
    canvas离屏、旋转效果实践——旋转的雪花
    走一步再走一步,揭开co的神秘面纱
    用javascript写一个emoji表情插件
    基于HTML5快速搭建TP-LINK电信拓扑设备面板
    百度地图获取规划路径信息
    devicePixelRatio 那些事儿
    怎样用JavaScript和HTML5 Canvas绘制图表
    首次写iPad布局感想(H5)
  • 原文地址:https://www.cnblogs.com/baron89/p/6888356.html
Copyright © 2011-2022 走看看