一般來說,在Android若要採用較高效能的Parcelable來做資料傳遞,我們需要在Model內實作【writeToParcel、describeContents、CREATOR】,
這實在是一個很繁雜的功夫,也就是前一篇提過的duplicate code,
還好,在我們使用了AutoValue後,就能一併使用另一個plugin(auto-value-parcel),順便解決這個煩死人的實作。
ps.關於Parcelable與Serializable的效能差異可以參考我的另一篇文章
Gradle:
//auto-value-parcel annotationProcessor 'com.ryanharter.auto.value:auto-value-parcel:0.2.5'
Before:
public class Book implements Parcelable {
private String name;
private int price;
private String author;
public Book(String name, int price, String author) {
this.name = name;
this.price = price;
this.author = author;
}
@Override
public String toString() {
return "Book{"
+ "name=" + name
+ ", price=" + price
+ ", author=" + author
+ "}";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public static final Parcelable.Creator<Book> CREATOR = new Parcelable.Creator<Book>() {
@Override
public Book createFromParcel(Parcel in) {
return new Book(
in.readString(),
in.readInt(),
in.readString()
);
}
@Override
public Book[] newArray(int size) {
return new Book[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(price);
dest.writeString(author);
}
}
After:
@AutoValue
public abstract class Book implements Parcelable {
public abstract String name();
public abstract int price();
public abstract String author();
public static Book create(String name, int price, String author) {
return new AutoValue_Book(name, price, author);
}
}
基本上在implement Parcelable 後,就不需要做事囉!
有沒有發現,我們的Model層越來越簡潔,越來越可愛了♡♡
延伸閱讀:
● 最簡潔的Model層 - AutoValue 使用介紹【一】
● 最簡潔的Model層 - AutoValue 使用介紹【三】