ReactiveCocoa取两个可能的信号?

时间:2015-06-27 18:33:36

标签: ios reactive-cocoa

所以我成功地将一个按钮变成了一个改变标签的关闭和开启开关。

我还能够在发生这种情况时启动定时处理,并且能够关闭定时进程。

无论如何我需要关闭定时过程我想知道是否有办法在不使用一次性物品的情况下阻止它。用第二个takeUntil信号。

编辑我认为我想要做的事情有点误导让我展示我现有的解决方案。

-(RACSignal*) startTimer {
    return [[RACSignal interval:1.0
            onScheduler:[RACScheduler mainThreadScheduler]]
             startWith:[NSDate date]];
}

-(void) viewWillAppear:(BOOL)animated {}

-(void) viewDidLoad {

    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    RACSignal* pressedStart = [self.start rac_signalForControlEvents:UIControlEventTouchUpInside];

    @weakify(self);
    RACSignal* textChangeSignal = [pressedStart map:^id(id value) {
        @strongify(self);
        return [self.start.titleLabel.text isEqualToString:@"Start"] ? @"Stop" : @"Start";
    }];

    // Changes the title
    [textChangeSignal subscribeNext:^(NSString* text) {
        @strongify(self);
        [self.start setTitle:text forState:UIControlStateNormal];
    }];

    RACSignal* switchSignal = [[textChangeSignal map:^id(NSString* string) {
        return [string isEqualToString:@"Stop"] ? @0 : @1;

    }] filter:^BOOL(id value) {
        NSLog(@"Switch %@",value);
        return [value boolValue];
    }];


    [[self rac_signalForSelector:@selector(viewWillAppear:)]
     subscribeNext:^(id x) {


    }];

    static NSInteger t = 0;
    // Remake's it self once it is on finished.
    self.disposable = [[[textChangeSignal filter:^BOOL(NSString* text) {
        return [text isEqualToString:@"Stop"] ? [@1 boolValue] : [@0 boolValue];
    }]
                                  flattenMap:^RACStream *(id value) {
                                      NSLog(@"Made new Sheduler");
                                      @strongify(self);
                                      return [[self startTimer] takeUntil:switchSignal];
                                  }] subscribeNext:^(id x) {
                                      NSLog(@"%@",x);
                                      @strongify(self);
                                      t = t + 1;
                                      NSLog(@"%zd",t);

                                      [self updateTable];
                                  }];

    [[self rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(id x) {
        NSLog(@"viewWillAppear Dispose");
        [self.disposable dispose];
    }];

}


-(BOOL) isGroupedExcercisesLeft {
    BOOL isGroupedLeft = NO;
    for (int i =0;i < [self.excercises count]; i++) {
        Excercise* ex = [self.excercises objectAtIndex:i];
        if(ex.complete == NO && ex.grouped == YES) {
            isGroupedLeft = YES;
            break;
        }
    }
    return isGroupedLeft;
}

-(void) updateTable {

    // Find the
    NSInteger nextRow;

    if (([self.excercises count] > 0 || self.excercises !=nil) && [self isGroupedExcercisesLeft]) {

        for (int i =0;i < [self.excercises count]; i++) {

            Excercise* ex = [self.excercises objectAtIndex:i];
            if(ex.complete == NO && ex.grouped == YES) {
                nextRow = i;
                break;
            }

        }

        NSIndexPath* path = [NSIndexPath indexPathForItem:nextRow inSection:0];
        NSArray* indexPath = @[path];
        // update //

        Excercise* ex = [self.excercises objectAtIndex:nextRow];
        [self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionTop animated:YES];
        if (ex.seconds <= 0) {
            RLMRealm* db = [RLMRealm defaultRealm];
            [db beginWriteTransaction];
            ex.complete = YES;
            [db commitWriteTransaction];
        }
        else {
            // Update Seconds
            RLMRealm* db = [RLMRealm defaultRealm];
            [db beginWriteTransaction];
            ex.seconds = ex.seconds - 1000;
            NSLog(@"Seconds: %zd",ex.seconds);
            [db commitWriteTransaction];
            // Update table
            [self.tableView reloadRowsAtIndexPaths:indexPath withRowAnimation:UITableViewRowAnimationNone];
        }


    } else {
        NSLog(@"Done");

        SIAlertView *alertView = [[SIAlertView alloc] initWithTitle:@"Deskercise" andMessage:@"Excercises Complete"];
        [alertView addButtonWithTitle:@"Ok"
                                 type:SIAlertViewButtonTypeDefault
                              handler:^(SIAlertView *alert) {

                              }];

        alertView.transitionStyle = SIAlertViewTransitionStyleBounce;
        [alertView show];
        NSLog(@"Dispose");
        [self.disposable dispose];

    }

}

1 个答案:

答案 0 :(得分:1)

使用takeUntil:self.completeSignal的问题是,当您将completeSignal更改为其他值时,它不会传递给任何已经等待completeSignal之前持有的变量的函数

- (RACSignal*) startTimer {
    @weakify(self)
    return [[[RACSignal interval:1.0
                 onScheduler:[RACScheduler mainThreadScheduler]]
         startWith:[NSDate date]]
        takeUntil:[[self.start rac_signalForControlEvents:UIControlEventTouchUpInside]
                   merge:[[RACObserve(self, completeSignal) skip:1] flattenMap:
                          ^RACStream *(RACSignal * signal) {
                              @strongify(self)
                              return self.completeSignal;
                          }]]
        ];
}

信号现在正在观察并展平completeSignal,这将产生预期的效果。 takeUntil:会忽略完成而不发送下一个事件的信号,因此请使用self.completedSignal = [RACSignal return:nil],它会发送一个下一个事件,然后完成。

然而,这段代码不是理想的,让我们看看更好的解决方案。

@property (nonatomic, readwrite) RACSubject * completeSignal;

- (RACSignal*) startTimer {
    return [[[RACSignal interval:1.0
                 onScheduler:[RACScheduler mainThreadScheduler]]
         startWith:[NSDate date]]
        takeUntil:[[self.start rac_signalForControlEvents:UIControlEventTouchUpInside]
                   merge:self.completeSignal]
        ];
}
- (void) viewDidLoad {
    [super viewDidLoad];
    self.completeSignal = [RACSubject subject];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    RACSignal * pressedStart = [self.start rac_signalForControlEvents:UIControlEventTouchUpInside];

    @weakify(self);
    RACSignal* textChangeSignal = [[pressedStart startWith:nil] scanWithStart:@"Stop" reduce:^id(id running, id next) {
        return @{@"Start":@"Stop", @"Stop":@"Start"}[running];
    }];

    [self.start
     rac_liftSelector:@selector(setTitle:forState:)
     withSignals:textChangeSignal, [RACSignal return:@(UIControlStateNormal)], nil];

    [[[pressedStart flattenMap:^RACStream *(id value) { //Using take:1 so that it doesn't get into a feedback loop
        @strongify(self);
        return [self startTimer];
    }] scanWithStart:@0 reduce:^id(NSNumber * running, NSNumber * next) {
        return @(running.unsignedIntegerValue + 1);
    }] subscribeNext:^(id x) {
        @strongify(self);
        [self updateTable];
        NSLog(@"%@", x);
    }];
}

- (void) updateTable {
    //If you uncomment these then it'll cause a feedback loop for the signal that calls updateTable

    //[self.start sendActionsForControlEvents:UIControlEventTouchUpInside];
    //[self.completeSignal sendNext:nil];
    if ([self.excercises count] > 0 || self.excercises !=nil) {
    } else {
    }
}

让我们浏览一下变化列表:

  • completeSignal现在是RACS主题(手动控制的RACSignal)。
  • 对于纯度和摆脱@weakify指令,textChangeSignal现在使用方便的scanWithStart:reduce:方法,它允许您访问累加器(这适用于与递增或递减数字)。
  • {li> start的文本现在由rac_liftSelector函数更改,该函数接受RACSignals并在所有函数都被触发时将其解包。
  • flattenMap: pressedStart替换[self startTimer] scanWithStart:reduce现在使用updateTable,这是一种更有效的方法来保持计数。

我不确定您是否通过flattenMap:包含完成信号进行测试,但肯定会导致pressedButton {{1}}出现逻辑问题,结果反馈循环最终会导致崩溃堆栈溢出时编程。