【问题标题】:Checking for nil model using reactive cocoa?使用反应性可可检查 nil 模型?
【发布时间】:2017-03-14 03:50:56
【问题描述】:

我想知道用反应可可检查 nil 值的方法是什么。

我假设我可以创建这样的信号。

// Turn state check into a signal to activate the rest
RACSignal* modelSignal = [self checkIfModelIsValid:self.model];

[[modelSignal then:^RACSignal *{
        return [self obtainImageSignal];
        // Always need to lazy call these functions
    }]
    subscribeNext:^(id x) {
        NSLog(@"It worked out! giving you null for fun though feel free to chain it? %@",x);
    }
    error:^(NSError *error) {
        // Replace with real ns error
        NSLog(@"Model or picture is nil: %@",error);
    } 
    completed:^{
        NSLog(@"Model this event started it all");
    }];

-(RACSignal *)obtainImageSignal {
    @weakify(self)
    RACSignal* imageSignal = [[NetworkManager sharedInstance] getImageWithImagePath:self.model.fullSizedPicture];

    // Processes that image signal
    [[imageSignal deliverOn:[RACScheduler mainThreadScheduler]]
         subscribeNext:^(UIImage* image) {
             @strongify(self)
             self.imageView.image = image;
             [self setUpTitle:self.model.title];
             [self setUpDescription:self.model.imageDescription];
         }
         error:^(NSError* error) {
             NSLog(@"Error: %@",[error description]);
         }
         completed:^{
             NSLog(@"Completed Operation: Image Retrieval Operation");
         }];

    return imageSignal;
}


-(RACSignal *) checkIfModelIsValid:(PhotoModel*) model {
    // Using then on this signal will force the image signal to handle the errors.?
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {

        if (self.model == nil || self.model.fullSizedPicture == nil) {
            [subscriber sendError:nil];
        }
        else {
            [subscriber sendNext:[NSNumber numberWithBool:YES]];
            [subscriber sendCompleted];
            // send complete for fun and see what it does
        }

        return nil;
    }];
}

或者是健全性检查不适用于反应函数式编程的情况?

【问题讨论】:

  • 我不确定我的问题是否清楚。是否要检查obtainImageSignal 是否返回零?
  • 你说得对,问题是风格或偏好问题,我应该这样标记。
  • 但是为什么ignore:nil、filter或map对你不起作用呢?
  • 是的,我应该使用 map 它可以忽略 nil 谢谢!
  • Operations like filter 可以在您想忽略 nil 值的情况下为您提供帮助

标签: reactive-programming reactive-cocoa


【解决方案1】:

只是为其他查看者举个例子,一种确保您没有从nil 模型中获取任何图像的方法 - 可以执行以下操作:

    RAC(self.someImageView, image) = [[RACObserve(self, model)
        filter:^BOOL(PhotoModel *currentModel) {
            return currentModel != nil;
        }]
        map:^id(PhotoModel *currentModel) {
            return [self someMethodToDownloadImageFromModel:currentModel];
        }];

请注意我是如何尝试避免在我的 RAC 块中使用 self 并避免注入在使用 subscribeNext:^then:^ 等时发生的副作用。这样一来,您的代码就更易于管理,而且 RAC 更高。

【讨论】:

  • 这不是ignore 方法的用途吗? [signal ignore:nil]
  • 是的,你绝对可以这样做@DougMcBride
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多