简体   繁体   中英

Android ViewModel with custom Model

I'm planning to have a model class and provide an instance of this model through an Android ViewModel. The instance in the ViewModel can change through the application lifecycle.

My current idea is like this:

public class Book {
    private MutableLiveData<String> mName = new MutableLiveData<>();

    public Book(...) {
        ...
    }

    public LiveData<String> getName() {
        return mName;
    }

    public void setName(String name) {
        mName.setValue(name);
    }
}

public class MyViewModel extends ViewModel {
    private MutableLiveData<Book> mCurrentBook = new MutableLiveData<>();
    private MutableLiveData<Book> mRecommendedBook = new MutableLiveData<>();

    public LiveData<Book> getCurrentBook() {
        return mCurrentBook;
    }

    public void setCurrentBook(Book book) {
        mCurrentBook.setValue(book);
    }
}

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);

        model.getCurrentBook().observe(this, book -> {
            book.getName().observe(this, name -> {
                // update UI
            });
        });
        ...
        model.setCurrentBook(someOtherBook);
    }
}

Is this a good approach? I'm not sure if it's a good idea to have the LiveData nested in another class.

Also could it be a problem that I'm creating a new observer for the book name, each time the book changes?

I answered a similar question here

You should use Transformation to carry data between your observer's.

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