ReactiveCocoa中的订阅-发布简写代码逻辑, 帮助理解流程

官网的RACSubject

  // 
  RACSubject *subject = [RACSubject subject];
        
  [subject subscribeNext:^(id x) {
      NSLog(@"x1 = %@", x);
   }];
        
  [subject subscribeNext:^(id x) {
      NSLog(@"x2 = %@", x);
   }];
        
   [subject sendNext:@"发送文字"];

NSLog

2020-04-11 01:14:50.17 x1 = 发送文字
2020-04-11 01:14:50.17 x2 = 发送文字

自己简写一套, 阉割了一些东西, 但是基本思想和官网一致

大致思路:
  • 创建一个NYLSubject继承自NSObject
  • 初始化NYLSubject的时候创建一个数组subscribers, 用来保存订阅者中的nextBlock
  • 当调用nyl_sendNex()的时候, 遍历subscribers, 取出里面的nextBlock, 执行block回调
下面看代码具体实现, 创建一个NYLSubject继承自NSObject

NYLSubject.h

@interface NYLSubject : NSObject

+ (instancetype)nyl_subject;
- (void)nyl_subsuribeNext:(void(^)(id x))nextBlock;
- (void)nyl_sendNext:(id)value;

@end

NYLSubject.m

//
//  NYLSubject.m
//  NYL_UnitTest
//
//  Created by 聂银龙 on 2020/4/11.
//  Copyright © 2020 聂银龙. All rights reserved.
//

#import "NYLSubject.h"

@interface NYLSubject()

/// 订阅者block
@property (nonatomic, copy) void(^next)(id x);
/// 订阅者数组(用来保存订阅者next)
@property (nonatomic, strong) NSMutableArray *subscribers;

@end

@implementation NYLSubject

+ (instancetype)nyl_subject {
    NYLSubject *subject = [[self alloc] init];
    return subject;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _subscribers = [[NSMutableArray alloc] initWithCapacity:1];
    }
    return self;
}

- (void)nyl_subsuribeNext:(void(^)(id x))nextBlock {
    NSCParameterAssert(nextBlock != NULL); // nextBlock为空就抛异常
    [_subscribers addObject:nextBlock];
}

- (void)nyl_sendNext:(id)value {
    [self.subscribers enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        void (^block)(id x) = obj;
        block(value);
    }];
}

@end

使用

 NYLSubject *nylSub = [NYLSubject nyl_subject];
        
 [nylSub nyl_subsuribeNext:^(id  _Nonnull x) {
      NSLog(@"自定义1 = %@", x);
  }];
        
 [nylSub nyl_subsuribeNext:^(id  _Nonnull x) {
      NSLog(@"自定义2 = %@", x);
  }];
        
 [nylSub nyl_sendNext:@"熬夜+1"];
  [nylSub nyl_sendNext:@"熬夜+2"];

Log
订阅两次打印两次,
send两次打印两次,
是不是跟官网的效果一致呢😄

自定义1 = 熬夜+1
自定义2 = 熬夜+1
自定义1 = 熬夜+2
自定义2 = 熬夜+2
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值