Android MVVM 解读 3. Android MVVM 介绍(4) Repositoy + DataBinding

2.5 Repository

没有过多需要描述的, 唯一需要区别的是返回值采用LiveData的方式, Demo 案例 来自google

class UserRepository {
   private val webservice: Webservice = TODO()
   // ...
   fun getUser(userId: String): LiveData<User> {
       // This isn't an optimal implementation. We'll fix it later.
       val data = MutableLiveData<User>()
       webservice.getUser(userId).enqueue(object : Callback<User> {
           override fun onResponse(call: Call<User>, response: Response<User>) {
               data.value = response.body()
           }
           // Error case is left out for brevity.
           override fun onFailure(call: Call<User>, t: Throwable) {
               TODO()
           }
       })
       return data
   }
}
final-architecture.png

根据此图, Repository的部分, 因为涉及到可能来自本地的数据源,或者来自网络的数据源,甚至会存在不同的数据有逻辑顺序的数据源,例如,先获取本地数据,在本地获取成功后,再次获取到远端的数据, 因而数据层,负责这些部分.

2.6 DataBinding

Google 官方说明: Data Binding Library

DataBinding Communication

DataBinding Communication.png

DataBinding Init Sequence

DataBinding Init Sequence.png

DataBindingUtil.sMapper的实现

/**
 * Inflates a binding layout and returns the newly-created binding for that layout.
 * This uses the DataBindingComponent set in
 * {@link #setDefaultComponent(DataBindingComponent)}.
 * <p>
 * Use this version only if <code>layoutId</code> is unknown in advance. Otherwise, use
 * the generated Binding's inflate method to ensure type-safe inflation.
 *
 * @param <T> Type of the generated binding class.
 * @param inflater The LayoutInflater used to inflate the binding layout.
 * @param layoutId The layout resource ID of the layout to inflate.
 * @param parent Optional view to be the parent of the generated hierarchy
 *               (if attachToParent is true), or else simply an object that provides
 *               a set of LayoutParams values for root of the returned hierarchy
 *               (if attachToParent is false.)
 * @param attachToParent Whether the inflated hierarchy should be attached to the
 *                       parent parameter. If false, parent is only used to create
 *                       the correct subclass of LayoutParams for the root view in the XML.
 * @return The newly-created binding for the inflated layout or <code>null</code> if
 * the layoutId wasn't for a binding layout.
 * @throws InflateException When a merge layout was used and attachToParent was false.
 * @see #setDefaultComponent(DataBindingComponent)
 */
// @Nullable don't annotate with Nullable. It is unlikely to be null and makes using it from
// kotlin really ugly. We cannot make it NonNull w/o breaking backward compatibility.
public static <T extends ViewDataBinding> T inflate(@NonNull LayoutInflater inflater,
        int layoutId, @Nullable ViewGroup parent, boolean attachToParent) {
    return inflate(inflater, layoutId, parent, attachToParent, sDefaultComponent);
}


/**
 * Inflates a binding layout and returns the newly-created binding for that layout.
 * <p>
 * Use this version only if <code>layoutId</code> is unknown in advance. Otherwise, use
 * the generated Binding's inflate method to ensure type-safe inflation.
 *
 * @param <T> Type of the generated binding class.
 * @param inflater The LayoutInflater used to inflate the binding layout.
 * @param layoutId The layout resource ID of the layout to inflate.
 * @param parent Optional view to be the parent of the generated hierarchy
 *               (if attachToParent is true), or else simply an object that provides
 *               a set of LayoutParams values for root of the returned hierarchy
 *               (if attachToParent is false.)
 * @param attachToParent Whether the inflated hierarchy should be attached to the
 *                       parent parameter. If false, parent is only used to create
 *                       the correct subclass of LayoutParams for the root view in the XML.
 * @param bindingComponent The DataBindingComponent to use in the binding.
 * @return The newly-created binding for the inflated layout or <code>null</code> if
 * the layoutId wasn't for a binding layout.
 * @throws InflateException When a merge layout was used and attachToParent was false.
 */
// @Nullable don't annotate with Nullable. It is unlikely to be null and makes using it from
// kotlin really ugly. We cannot make it NonNull w/o breaking backward compatibility.
public static <T extends ViewDataBinding> T inflate(
        @NonNull LayoutInflater inflater, int layoutId, @Nullable ViewGroup parent,
        boolean attachToParent, @Nullable DataBindingComponent bindingComponent) {
    final boolean useChildren = parent != null && attachToParent;
    final int startChildren = useChildren ? parent.getChildCount() : 0;
    final View view = inflater.inflate(layoutId, parent, attachToParent);
    if (useChildren) {
        return bindToAddedViews(bindingComponent, parent, startChildren, layoutId);
    } else {
        return bind(bindingComponent, view, layoutId);
    }
}


static <T extends ViewDataBinding> T bind(DataBindingComponent bindingComponent, View root,
        int layoutId) {
    return (T) sMapper.getDataBinder(bindingComponent, root, layoutId);
}

在Fragment中,采用inflate的方式时, 我们看到最终是需要通过变量sMapper来寻找到的, 而sMapper的实例是: DataBinderMapperImpl, 这块在源码中我们没有看到, 实现在哪里? 其实是我们在开启了
dataBinding {
enabled = true
}
时, 代码会自动生成,

在我们的application的工程(一般名字为app)中查找实现部分

    package android.databinding;
    public class DataBinderMapperImpl extends MergedDataBinderMapper {
    DataBinderMapperImpl() {
      addMapper(new com.test.app.DataBinderMapperImpl());// 将我们的application的DataBinderMapperImpl 注册
    }
    }

继续查看实现的com.test.app.DataBinderMapperImpl的实现

  package com.test.app;

  public class DataBinderMapperImpl extends DataBinderMapper {
  private static final SparseIntArray INTERNAL_LAYOUT_ID_LOOKUP = new SparseIntArray(0);

  static {
  }

  @Override
  public ViewDataBinding getDataBinder(DataBindingComponent component, View view, int layoutId) {
   int localizedLayoutId = INTERNAL_LAYOUT_ID_LOOKUP.get(layoutId);
   if(localizedLayoutId > 0) {
     final Object tag = view.getTag();
     if(tag == null) {
       throw new RuntimeException("view must have a tag");
     }
   }
   return null;
  }

  @Override
  public ViewDataBinding getDataBinder(DataBindingComponent component, View[] views, int layoutId) {
   if(views == null || views.length == 0) {
     return null;
   }
   int localizedLayoutId = INTERNAL_LAYOUT_ID_LOOKUP.get(layoutId);
   if(localizedLayoutId > 0) {
     final Object tag = views[0].getTag();
     if(tag == null) {
       throw new RuntimeException("view must have a tag");
     }
     switch(localizedLayoutId) {
     }
   }
   return null;
  }

  @Override
  public int getLayoutId(String tag) {
   if (tag == null) {
     return 0;
   }
   Integer tmpVal = InnerLayoutIdLookup.sKeys.get(tag);
   return tmpVal == null ? 0 : tmpVal;
  }

  @Override
  public String convertBrIdToString(int localId) {
   String tmpVal = InnerBrLookup.sKeys.get(localId);
   return tmpVal;
  }

  @Override
  public List<DataBinderMapper> collectDependencies() {
   ArrayList<DataBinderMapper> result = new ArrayList<DataBinderMapper>(1);
   result.add(new com.test.module.DataBinderMapperImpl());// 将Application的依赖的module注册进来
   return result;
  }

  private static class InnerBrLookup {
   static final SparseArray<String> sKeys = new SparseArray<String>(14);

   static {
     sKeys.put(0, "_all");
     sKeys.put(1, "image");
     sKeys.put(2, "item");
     sKeys.put(3, "onClick");
     sKeys.put(4, "data");
     sKeys.put(5, "visibility");
     sKeys.put(6, "vm");
     sKeys.put(7, "text");
     sKeys.put(8, "stepVm");
     sKeys.put(9, "type");
     sKeys.put(10, "retry");
     sKeys.put(11, "refundOnly");
     sKeys.put(12, "refundAndReturn");
   }
  }

  private static class InnerLayoutIdLookup {
   static final HashMap<String, Integer> sKeys = new HashMap<String, Integer>(0);

   static {
   }
  }
  }

通过上述的代码的分析得知,

  1. DataBindingUtil.sMapper的具体的实现,是通过代码生成器生成的
  2. 此mapper是在application的工程中,生成的类
  3. 此类,一般会有一个注册的mapper,为当前application的mapper
  4. application的mapper中,注册了其关联工程的mapper(这也是为什么, 我们的build.gradle中的dataBinding的enabled = true, 要从依赖的源头到application的工程一路注册,因为mapper,也是逐级传递的)
  5. 每个开启了dataBinding的enable=true的模块都有自己的DataBinderMapperImpl, 负责的是自己模块的dataBinding的处理和负责搜集子模块的DataBinderMapperImpl
  6. 通过这一系列的DataBinderMapperImpl, 在调用 DataBindUtils的方法
  static <T extends ViewDataBinding> T bind(DataBindingComponent bindingComponent, View root,
    int layoutId) {
return (T) sMapper.getDataBinder(bindingComponent, root, layoutId);

}
便可以找到对应的ViewDataBinding,并且初始化.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,406评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,732评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,711评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,380评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,432评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,301评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,145评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,008评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,443评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,649评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,795评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,501评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,119评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,731评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,865评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,899评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,724评论 2 354

推荐阅读更多精彩内容