eremzeit
eremzeit

Reputation: 4516

What is wrong with this simple `-flattenMap` ReactiveCocoa code?

After reading the README on -flattenMap several times I still can't figure out why this code isn't executing as expected. I should think that the code inside the block would be run twice but it's not getting hit at all. Am I missing something really silly? (I'm using v2.4.7) I also tried sending the values after I called -flattenMap in case it's an order thing. No dice.

RACSubject *test = [[RACSubject alloc] init];
[test sendNext:@1];
[test sendNext:@2];
[test sendCompleted];
[test flattenMap:^RACStream *(id value) {
  NSLog(@"here: %@", value);
  return [RACSignal return:@NO];
}];

Upvotes: 2

Views: 270

Answers (1)

Ian Henry
Ian Henry

Reputation: 22403

Two things:

The order does matter, since this is a subject, so change it to this:

RACSubject *test = [[RACSubject alloc] init];
[test flattenMap:^RACStream *(id value) {
    NSLog(@"here: %@", value);
    return [RACSignal return:@NO];
}];
[test sendNext:@1];
[test sendNext:@2];
[test sendCompleted];

Now, you're still not going to see anything -- because you haven't subscribed to it. You have merely created a signal that can do all this, but it's going to delay actually doing any work until you ask for it.

RACSubject *test = [[RACSubject alloc] init];
[[test flattenMap:^RACStream *(id value) {
    NSLog(@"here: %@", value);
    return [RACSignal return:@NO];
}] subscribeNext:^(id value) {
    NSLog(@"got a %@", value);
}];
[test sendNext:@1];
[test sendNext:@2];
[test sendCompleted];

Now, since there's a subscriber who actually wants to know about values, those sends will trigger as appropriate.

In the future, avoid putting side effects (like logging) anywhere except the blocks of the subscribe* and do* family of methods. flattenMap and other combinators want to be pure, so you'll see unexpected behavior like this if you violate that.

You probably know this, and are just testing out flattenMap, but your code can be simplified to just a map here -- flattenMap + return == map.

Upvotes: 2

Related Questions