Evgeniy Kleban
Evgeniy Kleban

Reputation: 6940

Understanding RACSubject

Im studying Reactive Cocoa and i wonder why following not work:

In class B i declare:

+(RACSubject*)importText{

    RACSubject *subject = [RACSubject subject];


    //1 block

    NSArray *testArray = @[@"1",@"2",@"3"];

    //2 block

    [subject sendNext:[[[testArray rac_sequence] map:^id(NSString* value) {

        return [value stringByAppendingString:@"More"];
    }] array]];



    return subject;
}

In class A:

 [[SecondObject importText] subscribeNext:^(id x) {

       NSLog(@"Output is %@", x);
   }];

However, nothing output in a console. Why?

Upvotes: 1

Views: 659

Answers (1)

REALFREE
REALFREE

Reputation: 4396

Take a look close to what importText method does. You first created a subject and temporary array. And then before any other stuffs happen, you just call sendNext:... to send the value you temporary created but no one else haven't subscribed the subject yet. And finally your importText method returns the subject which SecondObject will get and then subscribes to it.

@interface SomeClass
@property (nonatomic, strong) RACSubject *subject;
@end

@implementation SomeClass
- (id)init
{
    self = [super init];
    if(self) {
        self.subject = [RACSubject subject];
    }
}

- (RACSubject *)rac_signalForImportText
{
    return self.subject;
}

- (void)importText
{
    NSArray *testArray = @[@"1",@"2",@"3"];

    //2 block

    [subject sendNext:[[[testArray rac_sequence] map:^id(NSString* value) {

        return [value stringByAppendingString:@"More"];
    }] array]];
}



SomeClass* Second = [SomeClass alloc] init];
[[Second rac_signalForImportText] subscribeNext:^(id x) {
     NSLog(@"Output is %@", x);
}];
[Second importText];

I'm not sure why you want to use a subject in this way, but notice rac_signalForImportText won't get called until importText method call because that is where I use the subject to call sendNext which will trigger whoever subscribes on rac_signalForImportText. Hope this help.

Upvotes: 2

Related Questions