简体   繁体   English

具有自定义模型的Android ViewModel

[英]Android ViewModel with custom Model

I'm planning to have a model class and provide an instance of this model through an Android ViewModel. 我打算有一个模型类,并通过Android ViewModel提供此模型的实例。 The instance in the ViewModel can change through the application lifecycle. ViewModel中的实例可以在应用程序生命周期中进行更改。

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. 我不确定将LiveData嵌套在另一个类中是否是一个好主意。

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. 您应该使用Transformation在观察者之间传送数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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