RAC_2.RACSubject

2. RACSubject

  • 使用场景:通常用来代替代理,有了它,就不必要定义代理了。
  • 示例代码:
//    1.创建信号
    RACSubject *subject = [RACSubject subject];
//    2.订阅信号
    //不同的信号订阅的方式不一样!!(因为类型不一样,所以调用的方法不一样)
    //RACSubject处理订阅:拿到之前的_subscribers保存订阅者
    [subject subscribeNext:^(id x) {
        NSLog(@"接受到的数据:%@",x);
    }];
    //3.发送数据
    //遍历出所有的订阅者,调用nextBlock
    [subject sendNext:@"我想静静"];
  • 实际应用

JJView.h

#import <UIKit/UIKit.h>

#import <ReactiveObjC/ReactiveObjC.h>

@interface JJView : UIView

@property (nonatomic,strong) RACSubject *btnClickSingnal;

@end

JJView.m

-(RACSubject *)btnClickSingnal {
    if (!_btnClickSingnal) {
        _btnClickSingnal = [RACSubject subject];
    }
    return _btnClickSingnal;
}

- (instancetype)init {
    if (self == [super init]) {
        UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
        [button setBackgroundColor:[UIColor redColor]];
        [self addSubview:button];
        [button addTarget:self action:@selector(didClickButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return self;
}

- (void)didClickButton:(UIButton *)btn {
    NSLog(@"点了button");
    [self.btnClickSingnal sendNext:btn.backgroundColor];
}

SubjectViewController.m

#import "JJView.h"

@interface SubjectViewController ()
@property (nonatomic,strong) JJView *jjView;
@end

@implementation SubjectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    JJView *view = [[JJView alloc]init];
    view.backgroundColor = [UIColor yellowColor];
    view.frame = CGRectMake(10, 64, 400, 500);
    [view.btnClickSingnal subscribeNext:^(id  _Nullable x) {
        self.view.backgroundColor = x;
    }];
    [self.view addSubview:view];
    self.jjView = view;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,080评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,903评论 25 709
  • 不知何时,我对电脑游戏没了兴趣。当初的我可是一个不折不扣的游戏迷!游戏填充了我生命中那些斑驳的零星时光,带给...
    富顺阅读 173评论 0 2
  • 萝卜糕 奶奶柔弱的手中拿着几根刚出土的萝卜,泥土块、沙子和萝卜须缠绕在一起...
    uoiiou贱贱阅读 573评论 0 5
  • 榆木糖阅读 183评论 0 0