Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind Realm objects changes?

In my project im trying to work via MVVM, so in VM in .h file

  @property (nonatomic, strong) NSArray    *cities;

in .m file

  - (NSArray *)cities {
        return [[GPCity allObjects] valueForKey:@"name"];
    }

GPCity is a RLMObject subclass How to bind this via ReactiveCocoa (i mean see all cities updates/adds/removes) ?

Something like:

RAC(self, cities) = [[GPCity allObjects] map:(GPCity *)city {return city.name;}];
like image 586
Zaporozhchenko Oleksandr Avatar asked Jan 13 '16 14:01

Zaporozhchenko Oleksandr


1 Answers

You can wrap Realm change notifications in a RAC signal:

@interface RLMResults (RACSupport)
- (RACSignal *)gp_signal;
@end

@implementation RLMResults (RACSupport)
- (RACSignal *)gp_signal {
    return [RACSignal createSignal:^(id<RACSubscriber> subscriber) {
        id token = [self.realm addNotificationBlock:^(NSString *notification, RLMRealm *realm) {
            if (notification == RLMRealmDidChangeNotification) {
                [subscriber sendNext:self];
            }
        }];

        return [RACDisposable disposableWithBlock:^{
            [self.realm removeNotification:token];
        }];
    }];
}
@end

and then do:

RAC(self, cities) = [[[RLMObject allObjects] gp_signal]
                     map:^(RLMResults<GPCity *> *cities) { return [cities valueForKey:@"name"]; }];

This will unfortunately update the signal after every write transaction, and not just ones which modify cities. Once Realm 0.98 is released with support for per-RLMResults notifications, you'll be able to do the following, which will only update when a GPCity object is updated:

@interface RLMResults (RACSupport)
- (RACSignal *)gp_signal;
@end

@implementation RLMResults (RACSupport)
- (RACSignal *)gp_signal {
    return [RACSignal createSignal:^(id<RACSubscriber> subscriber) {
        id token = [self addNotificationBlock:^(RLMResults *results, NSError *error) {
            if (error) {
                [subscriber sendError:error];
            }
            else {
                [subscriber sendNext:results];
            }
        }];

        return [RACDisposable disposableWithBlock:^{
            [token stop];
        }];
    }];
}
@end
like image 168
Thomas Goyne Avatar answered Oct 13 '22 21:10

Thomas Goyne