OGeek|极客世界-中国程序员成长平台

标题: ios - ViewModel 完成操作时 ViewController 中的通知 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 15:09
标题: ios - ViewModel 完成操作时 ViewController 中的通知

我正在制作一个简单的 iOS 应用来学习 ReactiveCocoa。到目前为止,我一直在使用 XIB 文件,但决定切换到 Storyboard 。 在我的第一个 View 中,我有登录屏幕,当用户按下按钮时,viewModel 执行 RACCommand 来验证用户并下载他的联系人列表。之后我需要从 ViewController 调用 performSegueWithIdentifier: 来显示下载的数据。如何在 ViewController 中通知 viewModel 已成功完成其操作?

这是来自 ViewController 的代码片段:

RAC(self.viewModel, username) = self.usernameTextField.rac_textSignal;
RAC(self.viewModel, password) = self.passwordTextField.rac_textSignal;
self.loginButton.rac_command = self.viewModel.executeSignin;

以及来自其 ViewModel 的片段:

////////////////////////////////IN INIT////////////////////////////////////
self.executeSignin =
    [[RACCommand alloc] initWithEnabled:validAuthenticateSignal
                            signalBlock:^RACSignal *(id input) {
                                return  [self executeSigninSignal];
                            }];
//////////////////////////////////////////////////////////////////////////

-(RACSignal *)executpsigninsignal {
    return [[[self.services getAuthenticationService]
             authenticationSignalFor:self.username andPassword:self.password]
            //Return user if exists
            flattenMap:^RACStream *(STUser *user) {
                return [[[[[self services] getContactsLoadService]
                 contactsLoadSignalForUser:user] deliverOn:[RACScheduler mainThreadScheduler]]
                //Return user contacts
               doNext:^(NSArray *contacts) {
                   _downloadedContacts = [NSArray arrayWithArray:contacts];
               }];

            }];
}

我还尝试在 ViewController 中观察 ViewModels 下载的联系人属性:

RACSignal *contactsLoadSignal = RACObserve(self.viewModel, downloadedContacts);
[[contactsLoadSignal filter:^BOOL(NSArray *value) {
    return value!=nil && value.count>0;
}]subscribeNext:^(NSArray *array) {
    [self performSegueWithIdentifier"pushContactsList" sender:self];
}];

但这似乎不起作用,而且看起来并不好看。



Best Answer-推荐答案


您可以使用命令的 executionSignals 属性来做到这一点:

@weakify(self)
[executeSignin.executionSignals.switchToLatest filter:^BOOL(NSArray *value) {
    return value.count>0;  //nil check was redundant here
}] subscribeNext:^(NSArray *array) {
    @strongify(self)
    [self performSegueWithIdentifier"pushContactsList" sender:self];
}];

关于ios - ViewModel 完成操作时 ViewController 中的通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35901825/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4