ios - 在 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())
}
解决方案
对于 MVVM,你可能想在你的和之间使用Two Way data Binding
orObserver-Listener
模式,你可以参考MVVM Pattern进行参考。View
ViewModel
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
}
}
推荐阅读
- google-apps-script - 从工作表粘贴到文档时保留超链接
- r - 从字符串中提取引号中的单词
- linux - 在双插槽中——Linux 使用 CPU 插槽 1 和在 CPU 插槽 2 上运行的其他程序——如何防止内存区域重叠
- xaml - 在 Xamarin Forms 5.0.0 中找不到扩展器
- sql - 基于用户的数据库的别名/同义词
- ios - 具有在不同主机应用程序中使用的框架的 Cocoapods
- python - Django 图像附件 FileNotFoundError
- react-native - React Native - 从通知打开应用程序时获取初始路由
- java - 如何通过 JDBC 连接 mssql 数据库(启用 ssl。)
- ssl - 为什么使用 CNAME 时 SSL 证书不起作用?