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