Kelin-Hong / MVVMLight

A toolkit help to build Android MVVM Application
1.85k stars 333 forks source link

sample里面的代码不能算MVVM吧 #30

Closed vejei closed 4 years ago

vejei commented 5 years ago

ViewModel不是不能引用View也不关心View的吗?那为什么NewsViewModelNewsItemViewModel会有这样的代码:

// NewsViewModel构造器
public NewsViewModel(Fragment fragment) {
        this.fragment = fragment;

        BehaviorSubject<Notification<NewsService.News>> subject = BehaviorSubject.create();
        subject.filter(Notification::isOnNext)
                .subscribe(n -> Toast.makeText(fragment.getActivity(), "load finish!", Toast.LENGTH_SHORT).show());

        Observable.just(Calendar.getInstance())
                .doOnNext(c -> c.add(Calendar.DAY_OF_MONTH, 1))
                .map(c -> NewsListHelper.DAY_FORMAT.format(c.getTime()))
                .subscribe(d -> loadTopNews(d));
    }

这里竟然弹出Toast?难道Toast不算View或者View的一部分?

// NewsItemViewModel里面的代码
//command
    public ReplyCommand itemClickCommand = new ReplyCommand(() -> {
        this.viewStyle.titleTextColor.set(context.getResources().getColor(android.R.color.darker_gray));
        Intent intent = new Intent(context, NewsDetailActivity.class);
        intent.putExtra(NewsDetailActivity.EXTRA_KEY_NEWS_ID, storiesBean.getId());
        context.startActivity(intent);
    });

startActivity,也就是跳转到新的页面不是View的工作?为什么会由ViewModel来做?

这样还算是MVVM

Froyo91 commented 5 years ago

有类似的问题,也想请教下~

vejei commented 5 years ago

@Froyo91 官网文档:https://developer.android.com/topic/libraries/architecture/viewmodel#implement

Caution: A ViewModel must never reference a view, Lifecycle, or any class that may hold a reference to the activity context.

维基百科:https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel

The main difference between the view model and the Presenter in the MVP pattern, is that the presenter has a reference to a view whereas the view model does not. Instead, a view directly binds to properties on the view model to send and receive updates. To function efficiently, this requires a binding technology or generating boilerplate code to do the binding.

如果Toast也算作View或者View的一部分,这个就不能说是MVVM

KelinHong commented 5 years ago

不好意思,这边写的确实不是很严格,toast和跳转简单写了,严格上应该按接口方式放在view层去做的。在实际项目中,取决模块复杂程度程度,太严格遵守可能反而增加成长,这个要具体衡量,框架上也可以自由调整,我这个只是参考哈。

Froyo91 commented 5 years ago

感谢回答 @KelinHong @zeleven