简体   繁体   中英

Best way to share model (e.g. list of objects) between different ViewModels? [on hold]

I'm trying to undestand how to share data between two or more ViewModel, because i want to change property of object or several objects in ine fragment and see the changing data in a the other fragment immediately (eg on tablet when i can see two fragments in the same time).

I guess this is a completely architectural solution, but I'm new to this so I ask for advice that Best way to share model (eg list of objects) between different ViewModels.

You can use below steps to create viewmodel using android.os.Parcelable to share your object between fragments or activity.

import android.os.Parcel;
import android.os.Parcelable;

public class Student implements Parcelable {

    public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
        public Student createFromParcel(Parcel in) {
            return new Student(in);
        }

        public Student[] newArray(int size) {
            return new Student[size];
        }
    };

    private long id;
    private String name;
    private String grade;

    // Constructor
    public Student(long id, String name, String grade){
        this.id = id;
        this.name = name;
        this.grade = grade;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }

    // Parcelling part
       public Student(Parcel in){
           this.id = in.readLong();
           this.name = in.readString();
           this.grade =  in.readString();
       }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
       public void writeToParcel(Parcel dest, int flags) {
        dest.writeLong(this.id);
        dest.writeString(this.name);
        dest.writeString(this.grade);
       }

    @Override
    public String toString() {
        return "Student{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", grade='" + grade + '\'' +
                '}';
    }
}

Use below bundle and pass your model arraylist to bunlde and share bundle among fragments or activity.

Bundle bundle = new Bundle();
bundle.putParcelableArrayList("key", new ArrayList<Student>())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM