【问题标题】:How to organise and name code when working in MVVM在 MVVM 中工作时如何组织和命名代码
【发布时间】:2018-12-22 13:17:51
【问题描述】:

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

如果我有一个类负责为视图模型提供有关用户配置文件的数据并触发异步 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())
}

【问题讨论】:

  • 许多好的问题会根据专家的经验产生一定程度的意见,但这个问题的答案往往几乎完全基于意见,而不是事实、参考资料或特定专业知识。

标签: ios swift mvvm


【解决方案1】:

对于 MVVM,您可能希望在 ViewViewModel 之间使用 Two Way data BindingObserver-Listener 模式,您可以参考 MVVM Pattern 以供参考。

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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    • 2020-02-28
    • 1970-01-01
    • 2014-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多