RACCommand error信号回调随笔

ViewModel创建RACCommand:

-(RACCommand *)command{

    if(!_command){

        _command =[[RACCommand alloc]initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input){

            return[self signal];

        }];

    }

    return _command;

}

-(RACSignal *)signal{

    return[RACSignal createSignal:^RACDisposable * _Nullable(id  _Nonnull subscriber){

        [[RequestManager sharedManager]showHud:YES successBlock:^(NSDictionary *response){

            [subscriber sendNext:Model];

            [subscriber sendCompleted];

        } failureBlock:^(NSError *error){

            [subscriber sendError:error];

            [subscriber sendCompleted];

        }];

        return nil;

    }];

}

在View层调用Command:

 [self.viewModel.couponDetailCommand.executionSignals.switchToLatest subscribeNext:^(id  _Nullable x){

        [self showCouponDetailView];

    }error:^(NSError * _Nullable error){

        NSLog()

    }];

 [self.viewModel.couponDetailCommand execute:@1];

这种方式viewModel中sendError得话是收不到回调。

解决方案:

一、更改为:

    [[self.viewModel.couponDetailCommand execute:@{}]subscribeNext:^(id  _Nullable x){

        [self showCouponDetailView];

    }error:^(NSError * _Nullable error){

        [self showNormalView];

    }];

二、使用Command的error信号

[self.viewModel.couponDetailCommand.executionSignals.switchToLatest subscribeNext:^(id  _Nullable x){

        //请求成功

    }];

 [self.viewModel.couponDetailCommand.errors subscribeNext:^(NSError * _Nullable x){

        //请求失败

 }];

三、使用materialize和dematerialize

materialize将所有的信号封装成event一并回调,但会导致Command对象中error、executing等信号无回调,不建议使用

-(RACCommand *)couponDetailCommand{

    if(!_couponDetailCommand){


        _couponDetailCommand =[[RACCommand alloc]initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input){

            return[[self signal]materialize];

        }];

    }

    return _couponDetailCommand;

}

[self.viewModel.couponDetailCommand.executionSignals subscribeNext:^(RACSignal *execution){

        [[[execution dematerialize]deliverOn:[RACScheduler mainThreadScheduler]]subscribeError:^(NSError *error){

            NSLog(@"发生错误");

        } completed:^{

            NSLog(@"完成");

        }];

 }];

你可能感兴趣的:(RACCommand error信号回调随笔)