iOS进阶指南

RAC中的RACLifting

2016-12-02  本文已影响0人  一只二进制编码的狗

一开始不太知道这个方法,后来看别人在用就看了下源码,其实也很简单,用了会比较方便,不用也可以用别的形式代替。先看看用法吧。

    RACSignal *signald = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        [subscriber sendNext:RACTuplePack(@"haha")];
        return [RACDisposable disposableWithBlock:^{
            NSLog(@"disposable");
        }];
    }];
    
    [[self rac_liftSelector:@selector(testVoid:) withSignalOfArguments:signald] subscribeNext:^(id x) {
        NSLog(@"%@", x);
    }];

其实就是signal的sendNext的值做为方法的入参,有个注意的地方就是sendNext的必需是个RACTuple,所以要包下。方法的返回值会再被sendNext,看看源码,很简单。

- (RACSignal *)rac_liftSelector:(SEL)selector withSignalOfArguments:(RACSignal *)arguments {
    NSCParameterAssert(selector != NULL);
    NSCParameterAssert(arguments != nil);
    
    @unsafeify(self);
    
    NSMethodSignature *methodSignature = [self methodSignatureForSelector:selector];
    NSCAssert(methodSignature != nil, @"%@ does not respond to %@", self, NSStringFromSelector(selector));
    //会订阅这个信号,拿到返回值然后执行这个方法,然后把得到的返回值返回回去
    return [[[[arguments
        takeUntil:self.rac_willDeallocSignal]
        map:^(RACTuple *arguments) {
            @strongify(self);
            
            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
            invocation.selector = selector;
            invocation.rac_argumentsTuple = arguments;
            [invocation invokeWithTarget:self];
            
            return invocation.rac_returnValue;
        }]
        replayLast]
        setNameWithFormat:@"%@ -rac_liftSelector: %s withSignalsOfArguments: %@", self.rac_description, sel_getName(selector), arguments];
}

还有一些的方法,用法一样

/// Like -rac_liftSelector:withSignals:, but accepts an array instead of
/// a variadic list of arguments.
- (RACSignal *)rac_liftSelector:(SEL)selector withSignalsFromArray:(NSArray *)signals;

/// Like -rac_liftSelector:withSignals:, but accepts a signal sending tuples of
/// arguments instead of a variadic list of arguments.
- (RACSignal *)rac_liftSelector:(SEL)selector withSignalOfArguments:(RACSignal *)arguments;
上一篇下一篇

猜你喜欢

热点阅读