开源项目Plaid学习(一)

前言

Material Design(简称MD)是谷歌近来大力推行的安卓设计风格,其中包含了诸多设计原则、控件表现以及动画。
当然设计只是设计,设计师不管实现,那一个个炫酷的设计的实现只能靠码农来做。目前Github上面也有不少MD的工具库,但是大部分都是零零碎碎的,这里一个Edit Text控件,那里一个Calendar控件。一些号称遵循MD风格的开源App也是只实现了很小的一部分,尤其是MD的过渡和动画,这部分我认为是比较难的。
最终我找到了Plaid这个项目。该项目的作者是谷歌员工,里面使用了大量的自定义控件,可能从架构层面上不是非常突出,没有Event bus,没有Rxjava,沟通靠的是接口和推送,但在UI这方面,这款App是我目前为止见过在MD方面最出色的。
说实话这个App不小,想在短时间内消化完是不太现实的。还是慢慢来比较科学。

依赖项目

Min SDK是21,因为从Lollipop之后谷歌才真正把MD给定下来。

dependencies {
    compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'
    compile "com.android.support:customtabs:${supportLibVersion}"
    compile "com.android.support:design:${supportLibVersion}"
    compile "com.android.support:palette-v7:${supportLibVersion}"
    compile "com.android.support:recyclerview-v7:${supportLibVersion}"
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.github.bumptech.glide:okhttp3-integration:1.4.0@aar'
    compile 'com.google.code.gson:gson:2.8.0'
    compile 'com.jakewharton:butterknife:8.4.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.squareup.okhttp3:okhttp:3.4.2'
    compile 'org.jsoup:jsoup:1.10.1'
    compile project(':bypass')
}

大部分库还是很熟悉,Bypass看介绍说是跳过Html直接处理markdown。可以发现这个App对于处理WebView有比较大的需求。也不奇怪,主要就是UI的展示,业务逻辑可以不依赖外界库。

data文件夹浅析

app文件夹主要有3个大的文件夹,data,ui和util。
Data文件夹里面放有几乎所有和数据相关的java文件,包括POJO,DataManager,WebService和PrefManager等等,负责网络数据和本地数据的读写,以retrofit+OkHttp作为网络底层,再由DataManager进行封装来给UI层提供数据服务。见下图:


data文件

可能需要稍微解释一下。主要的数据有三种,即designer news,dribbble和producthunt,这三种数据都继承PlaidItem。
各种DataManager都是继承的BaseDataManager,而这个类又是基于DataLoadingSubject这个接口:

/**
 * An interface for classes offering data loading state to be observed.
 */
public interface DataLoadingSubject {
    boolean isDataLoading();
    void registerCallback(DataLoadingCallbacks callbacks);
    void unregisterCallback(DataLoadingCallbacks callbacks);

    interface DataLoadingCallbacks {
        void dataStartedLoading();
        void dataFinishedLoading();
    }
}

这个接口主要就是为数据加载提供开始和结束的两个回调。
再看看BaseDataManager这个基类,虽然有点长,但是这个类算是App数据处理的核心,所以还是贴出来:

/**
 * Base class for loading data; extending types are responsible for providing implementations of
 * {@link #onDataLoaded(Object)} to do something with the data and {@link #cancelLoading()} to
 * cancel any activity.
 */
public abstract class BaseDataManager<T> implements DataLoadingSubject {

    private final AtomicInteger loadingCount;
    private final DesignerNewsPrefs designerNewsPrefs;
    private final DribbblePrefs dribbblePrefs;
    private DribbbleSearchService dribbbleSearchApi;
    private ProductHuntService productHuntApi;
    private List<DataLoadingSubject.DataLoadingCallbacks> loadingCallbacks;

    public BaseDataManager(@NonNull Context context) {
        loadingCount = new AtomicInteger(0);
        designerNewsPrefs = DesignerNewsPrefs.get(context);
        dribbblePrefs = DribbblePrefs.get(context);
    }

    public abstract void onDataLoaded(T data);

    public abstract void cancelLoading();

    @Override
    public boolean isDataLoading() {
        return loadingCount.get() > 0;
    }

    public DesignerNewsPrefs getDesignerNewsPrefs() {
        return designerNewsPrefs;
    }

    public DesignerNewsService getDesignerNewsApi() {
        return designerNewsPrefs.getApi();
    }

    public DribbblePrefs getDribbblePrefs() {
        return dribbblePrefs;
    }

    public DribbbleService getDribbbleApi() {
        return dribbblePrefs.getApi();
    }

    public ProductHuntService getProductHuntApi() {
        if (productHuntApi == null) createProductHuntApi();
        return productHuntApi;
    }

    public DribbbleSearchService getDribbbleSearchApi() {
        if (dribbbleSearchApi == null) createDribbbleSearchApi();
        return dribbbleSearchApi;
    }

    @Override
    public void registerCallback(DataLoadingSubject.DataLoadingCallbacks callback) {
        if (loadingCallbacks == null) {
            loadingCallbacks = new ArrayList<>(1);
        }
        loadingCallbacks.add(callback);
    }

    @Override
    public void unregisterCallback(DataLoadingSubject.DataLoadingCallbacks callback) {
        if (loadingCallbacks != null && loadingCallbacks.contains(callback)) {
            loadingCallbacks.remove(callback);
        }
    }

    protected void loadStarted() {
        if (0 == loadingCount.getAndIncrement()) {
            dispatchLoadingStartedCallbacks();
        }
    }

    protected void loadFinished() {
        if (0 == loadingCount.decrementAndGet()) {
            dispatchLoadingFinishedCallbacks();
        }
    }

    protected void resetLoadingCount() {
        loadingCount.set(0);
    }

    protected static void setPage(List<? extends PlaidItem> items, int page) {
        for (PlaidItem item : items) {
            item.page = page;
        }
    }

    protected static void setDataSource(List<? extends PlaidItem> items, String dataSource) {
        for (PlaidItem item : items) {
            item.dataSource = dataSource;
        }
    }

    protected void dispatchLoadingStartedCallbacks() {
        if (loadingCallbacks == null || loadingCallbacks.isEmpty()) return;
        for (DataLoadingCallbacks loadingCallback : loadingCallbacks) {
            loadingCallback.dataStartedLoading();
        }
    }

    protected void dispatchLoadingFinishedCallbacks() {
        if (loadingCallbacks == null || loadingCallbacks.isEmpty()) return;
        for (DataLoadingCallbacks loadingCallback : loadingCallbacks) {
            loadingCallback.dataFinishedLoading();
        }
    }

    private void createDribbbleSearchApi() {
        dribbbleSearchApi = new Retrofit.Builder()
                .baseUrl(DribbbleSearchService.ENDPOINT)
                .addConverterFactory(new DribbbleSearchConverter.Factory())
                .build()
                .create((DribbbleSearchService.class));
    }

    private void createProductHuntApi() {
        final OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new AuthInterceptor(BuildConfig.PROCUCT_HUNT_DEVELOPER_TOKEN))
                .build();
        final Gson gson = new Gson();
        productHuntApi = new Retrofit.Builder()
                .baseUrl(ProductHuntService.ENDPOINT)
                .client(client)
                .addConverterFactory(new DenvelopingConverter(gson))
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build()
                .create(ProductHuntService.class);
    }

}

这个基类有不少方法,但大多都比较简单。
AtomicInteger以前没有接触过,查了一下是一个线程安全的整数,也就是说不用担心竞争。loadingCount这个参数是指示加载状态的重要参数,而这个值使用AtomicInteger的做法具有参考价值。
两个Prefs类负责处理相关的SharedPreference。事实上,这两个类远不止处理SharedPreference那么简单,还处理和用户登录的一些信息,并能够返回相关的网络Service Api。说实话这样的设计有点奇怪,不过也可以说登录信息也是SharedPreference要负责的东西,所以也还可以接受。
然后有获得三种Api的函数。
回调接口是以数组形式存在的,也就是说可以有多个,然后可以删减,不过调用的时候都是一起调用。
而后其他的各类DataManager都继承这个基类。

data文件夹内还有一些Weigher,用来帮助对item进行排序。

还有一个值得一提的就是自定义的一个Envelope注释,用来和一个Gson的转换方法一起,实现只抽取关心的Json内容。

/**
 * An annotation for identifying the payload that we want to extract from an API response wrapped in
 * an envelope object.
 */
@Target(METHOD)
@Retention(RUNTIME)
public @interface EnvelopePayload {
    String value() default "";
}
/**
 * A {@link retrofit2.Converter.Factory} which removes unwanted wrapping envelopes from API
 * responses.
 */
public class DenvelopingConverter extends Converter.Factory {

    final Gson gson;

    public DenvelopingConverter(@NonNull Gson gson) {
        this.gson = gson;
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(
            Type type, Annotation[] annotations, Retrofit retrofit) {

        // This converter requires an annotation providing the name of the payload in the envelope;
        // if one is not supplied then return null to continue down the converter chain.
        final String payloadName = getPayloadName(annotations);
        if (payloadName == null) return null;

        final TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new Converter<ResponseBody, Object>() {
            @Override
            public Object convert(ResponseBody body) throws IOException {
                try (JsonReader jsonReader = gson.newJsonReader(body.charStream())) {
                    jsonReader.beginObject();
                    while (jsonReader.hasNext()) {
                        if (payloadName.equals(jsonReader.nextName())) {
                            return adapter.read(jsonReader);
                        } else {
                            jsonReader.skipValue();
                        }
                    }
                    return null;
                } finally {
                    body.close();
                }
            }
        };
    }

    private @Nullable String getPayloadName(Annotation[] annotations) {
        if (annotations == null) return null;
        for (Annotation annotation : annotations) {
            if (annotation instanceof EnvelopePayload) {
                return ((EnvelopePayload) annotation).value();
            }
        }
        return null;
    }
}

这个实现说不上多优雅,基本是属于暴力破解,好处就是省事,和retrofit2一起使用就不用对Response也写一个类了。有一定参考价值,不过如果是长期项目的话,还是应该对Response也写一个类。而且假如Response都类似的话,可能还可以搞一个泛型的数据数组,然后复用。

总的来说,这个App网络访问的任务还是不少的,包括三类数据,filter选项,search选项,登录功能,以及附带的一些点赞、查看人数、评论等等功能。
有很多地方没有介绍到,但是这个App主要的参考价值并不在数据访问和处理上,而在于UI和自定义控件以及炫酷的动画上,因此对于数据方面大概知道是干嘛的就行了。
接下来的一篇文章将对UI进行分析。说实话我也不知道要写多少,可以写的东西肯定不少,只是如果每一个都写也有点啰嗦,那就到时候再说吧。

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

推荐阅读更多精彩内容