DIR*_*AVE 6 android clean-architecture android-mvvm
我正在尝试学习 MVVM 以使我的应用程序的架构更加干净。但我很难掌握如何为我的应用程序创建“域”层。
目前,我的项目结构如下:
我的View是活动。我ViewModel有一个活动可以调用的公共方法。一旦调用 ViewModel 中的方法,它就会调用我的Repository类中的一个方法,该方法执行网络调用,然后将数据返回到 ViewModel。然后,我更新LiveDataViewModel 中的 ,以便更新 Activity 的 UI。
这就是我对如何Domain向结构添加层感到困惑的地方。我读过很多关于 Domain 层的 Stackoverflow 答案和博客,它们大多告诉您从 Domain 层中删除所有业务逻辑ViewModel并创建一个纯 Java/Kotlin 类。
所以而不是
View --> ViewModel --> Repository
我将从 与班级进行通信ViewModel,Domain班级Domain将与 进行通信Repository?
View --> ViewModel --> Domain --> Repository
我用我的电话给班级RxJava打电话。ViewModelRepository
@HiltViewModel
public class PostViewModel extends ViewModel {
private static final String TAG = "PostViewModel";
private final List<Post> listPosts = new ArrayList<>();
private final MutableLiveData<List<Post>> getPostsLiveData = new MutableLiveData<>();
private final MutableLiveData<Boolean> centerProgressLiveData = new MutableLiveData<>();
private final MainRepository repository;
@Inject
public PostViewModel(MainRepository repository) {
this.repository = repository;
getSubredditPosts();
}
public void getSubredditPosts() {
repository.getSubredditPosts()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Response>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
centerProgressLiveData.setValue(true);
}
@Override
public void onNext(@NonNull Response response) {
Log.d(TAG, "onNext: Query called");
centerProgressLiveData.setValue(false);
listPosts.clear();
listPosts.addAll(response.getData().getChildren());
getPostsLiveData.setValue(listPosts);
}
@Override
public void onError(@NonNull Throwable e) {
Log.e(TAG, "onError: getPosts", e);
centerProgressLiveData.setValue(false);
}
@Override
public void onComplete() {
}
});
}
Run Code Online (Sandbox Code Playgroud)
public class MainRepository {
private final MainService service;
@Inject
public MainRepository(MainService service) {
this.service = service;
}
public Observable<Response> getSubredditPosts() {
return service.getSubredditPosts();
}
}
Run Code Online (Sandbox Code Playgroud)
有人可以给我一个例子来说明我该怎么做吗?我在这里很迷路
我在尝试弄清楚域层时遇到了困难。\n最常见的例子是用例。
\n您的视图模型不会直接与存储库通信。正如您所说,您需要 viewmodel \xe3\x80\x8bdomain \xe3\x80\x8brepository。
\n您可能会将用例视为每个存储库方法的抽象。
\n假设您有一个电影存储库,您可以在其中调用电影列表的方法、电影详细信息的另一个方法以及相关电影的第三个方法。
\n每个方法都有一个用例。
\n其目的是什么?
\n假设您有一个与详细视图模型通信的 DetailActivity。您的视图模型不需要知道所有存储库(在详细信息屏幕上调用电影列表方法的目的是什么?)。因此,您的 DetailViewModel 将知道的只是“详细用例”(调用存储库中的详细方法)。
\nGoogle 几个小时前更新了架构文档,请看一下!\n https://android-developers.googleblog.com/2021/12/rebuilding-our-guide-to-app-architecture.html?m=1&s= 09
\nPS:Usecase 不是一个特殊的 Android 类,您不需要固有任何行为(如片段、活动、视图模型...),它是一个普通的类,它将接收存储库作为参数。
\n你会得到类似的东西:
\n视图模型:
\nfunction createPost(post Post){\n createUseCase.create(post)\n}\nRun Code Online (Sandbox Code Playgroud)\n用例
\nfunction createPost(post Post): Response {\n return repository.create(post)\n}\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
2518 次 |
| 最近记录: |