官网的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