首页 > 解决方案 > 在 MVVM 中工作时如何组织和命名代码

问题描述

我不确定在设计我的代码时,我是否应该使用类“服务”来为我的视图模型捆绑逻辑?

如果我有一个类负责为视图模型提供有关用户配置文件的数据并触发异步 api 调用,我应该将它放在一个文件中,例如ProfileService

Angular 中的约定类似于profile.service.ts- 这个类会被称为“服务”吗?还是在 Swift 中有更好的模式?

我正在尝试使用 Swift 我的第一个 iOS 应用程序。我的背景是前端网络,我热衷于不带出在 Swift / iOS 开发中不是最佳实践的习惯。

我猜一个例子是这样的:

class MyProfileService {
    func fetchUserProfile() {
        /*
            Perform some async network call
        */
    }
}

class MyViewModel {
    let profileService: MyProfileService
    init(profileService: MyProfileService) {
        self.profileService = profileService
    }
}

class MyClass {
    let viewModel = MyViewModel(profileService: MyProfileService())
}

标签: iosswiftmvvm

解决方案


对于 MVVM,你可能想在你的和之间使用Two Way data BindingorObserver-Listener模式,你可以参考MVVM Pattern进行参考。ViewViewModel

class MyProfileService {
    func fetchUserProfile() {
        /*
            Perform some async network call
        */
    }
}

class MyViewModel {
    var name: Observable<String?> = Observable()

    let profileService: MyProfileService
    init(profileService: MyProfileService) {
        self.profileService = profileService
    }
}

class MyClass {
    let viewModel = MyViewModel(profileService: MyProfileService())

    //observe the change in name property and do your task
    viewModel.observe(for: [viewModel.name]) { [weak self] (_) in
        // perform your task once name property is set
    }
}

推荐阅读