NSUserDefaults+RACSupport.m 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. //
  2. // NSUserDefaults+RACSupport.m
  3. // ReactiveCocoa
  4. //
  5. // Created by Matt Diephouse on 12/19/13.
  6. // Copyright (c) 2013 GitHub, Inc. All rights reserved.
  7. //
  8. #import "NSUserDefaults+RACSupport.h"
  9. #import <ReactiveCocoa/EXTScope.h>
  10. #import "NSNotificationCenter+RACSupport.h"
  11. #import "NSObject+RACDeallocating.h"
  12. #import "RACChannel.h"
  13. #import "RACScheduler.h"
  14. #import "RACSignal+Operations.h"
  15. @implementation NSUserDefaults (RACSupport)
  16. - (RACChannelTerminal *)rac_channelTerminalForKey:(NSString *)key {
  17. RACChannel *channel = [RACChannel new];
  18. RACScheduler *scheduler = [RACScheduler scheduler];
  19. __block BOOL ignoreNextValue = NO;
  20. @weakify(self);
  21. [[[[[[[NSNotificationCenter.defaultCenter
  22. rac_addObserverForName:NSUserDefaultsDidChangeNotification object:self]
  23. map:^(id _) {
  24. @strongify(self);
  25. return [self objectForKey:key];
  26. }]
  27. startWith:[self objectForKey:key]]
  28. // Don't send values that were set on the other side of the terminal.
  29. filter:^ BOOL (id _) {
  30. if (RACScheduler.currentScheduler == scheduler && ignoreNextValue) {
  31. ignoreNextValue = NO;
  32. return NO;
  33. }
  34. return YES;
  35. }]
  36. distinctUntilChanged]
  37. takeUntil:self.rac_willDeallocSignal]
  38. subscribe:channel.leadingTerminal];
  39. [[channel.leadingTerminal
  40. deliverOn:scheduler]
  41. subscribeNext:^(id value) {
  42. @strongify(self);
  43. ignoreNextValue = YES;
  44. [self setObject:value forKey:key];
  45. }];
  46. return channel.followingTerminal;
  47. }
  48. @end