开源项目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层提供数据服务。见下图:


开源项目Plaid学习(一)_第1张图片
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 implements DataLoadingSubject {

    private final AtomicInteger loadingCount;
    private final DesignerNewsPrefs designerNewsPrefs;
    private final DribbblePrefs dribbblePrefs;
    private DribbbleSearchService dribbbleSearchApi;
    private ProductHuntService productHuntApi;
    private List 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 items, int page) {
        for (PlaidItem item : items) {
            item.page = page;
        }
    }

    protected static void setDataSource(List 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 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() {
            @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进行分析。说实话我也不知道要写多少,可以写的东西肯定不少,只是如果每一个都写也有点啰嗦,那就到时候再说吧。

你可能感兴趣的:(开源项目Plaid学习(一))