我将RxSwift
与MVVM
一起使用。我有一种情况,我加载了一个问题的屏幕。每个都由QuestionViewModel
表示,其中包含问题,questionAnswer
表示为Drivers
。我遇到的问题是我想保存QuestionViewModels
的答案,但只有当他们按下主屏幕上的保存按钮时才会这样。它很容易订阅,当一个问题被单独回答时,但这会按下每个按钮,而不是我想要一次保存,因为他们可以按下并想要取消。
struct ClientProfileViewModel {
private let service: Service
private let client: Client?
let questionnaire: Observable<Questionnaire>
let answerViewModels: Observable<[QuestionViewModel]>
init(service: Service, client: Client?) {
self.service = service
self.client = client
self.questionnaire = self.service.questionnaire(client: client)
self.answerViewModels = self.questionnaire.map { (questionnaire) -> [QuestionViewModel] in
return questionnaire.questions.map { question in
let answer = client?.answers.first(where: { (qa) -> Bool in
return qa.question.questionId == question.questionId
}) ?? QuestionAnswer(question: question, answerYesNo: nil, answerText: nil)
return QuestionViewModel(question: question, answer: answer)
}
}
}
}
struct QuestionViewModel {
private let question: Question
private let answer: QuestionAnswer
let questionOutput: Driver<Question>
let answerOutput: Driver<QuestionAnswer>
init(question: Question, answer: QuestionAnswer) {
self.question = question
self.answer = answer
self.questionOutput = BehaviorRelay<Question>(value: self.question).asDriver()
self.answerOutput = BehaviorRelay<QuestionAnswer>(value: self.answer).asDriver()
}
}
有什么想法吗?