forked from xBlackMilk/RACCommandExample
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubscribeViewModel.m
More file actions
73 lines (60 loc) · 2.24 KB
/
SubscribeViewModel.m
File metadata and controls
73 lines (60 loc) · 2.24 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//
// Created by Ole Gammelgaard Poulsen on 05/12/13.
// Copyright (c) 2012 SHAPE A/S. All rights reserved.
//
#import "SubscribeViewModel.h"
#import "AFHTTPRequestOperationManager+RACSupport.h"
#import "NSString+EmailAdditions.h"
static NSString *const kSubscribeURL = @"http://reactivetest.apiary.io/subscribers";
@interface SubscribeViewModel ()
@property(nonatomic, strong) RACSignal *emailValidSignal;
@end
@implementation SubscribeViewModel
- (id)init {
self = [super init];
if (self) {
[self mapSubscribeCommandStateToStatusMessage];
}
return self;
}
- (void)mapSubscribeCommandStateToStatusMessage {
RACSignal *startedMessageSource = [self.subscribeCommand.executionSignals map:^id(RACSignal *subscribeSignal) {
return NSLocalizedString(@"Sending request...", nil);
}];
RACSignal *completedMessageSource = [self.subscribeCommand.executionSignals flattenMap:^RACStream *(RACSignal *subscribeSignal) {
return [[[subscribeSignal materialize] filter:^BOOL(RACEvent *event) {
return event.eventType == RACEventTypeCompleted;
}] map:^id(id value) {
return NSLocalizedString(@"Thanks", nil);
}];
}];
RACSignal *failedMessageSource = [[self.subscribeCommand.errors subscribeOn:[RACScheduler mainThreadScheduler]] map:^id(NSError *error) {
return NSLocalizedString(@"Error :(", nil);
}];
RAC(self, statusMessage) = [RACSignal merge:@[startedMessageSource, completedMessageSource, failedMessageSource]];
}
- (RACCommand *)subscribeCommand {
if (!_subscribeCommand) {
@weakify(self);
_subscribeCommand = [[RACCommand alloc] initWithEnabled:self.emailValidSignal signalBlock:^RACSignal *(id input) {
@strongify(self);
return [SubscribeViewModel postEmail:self.email];
}];
}
return _subscribeCommand;
}
+ (RACSignal *)postEmail:(NSString *)email {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer new];
NSDictionary *body = @{@"email": email ?: @""};
return [[[manager rac_POST:kSubscribeURL parameters:body] logError] replayLazily];
}
- (RACSignal *)emailValidSignal {
if (!_emailValidSignal) {
_emailValidSignal = [RACObserve(self, email) map:^id(NSString *email) {
return @([email isValidEmail]);
}];
}
return _emailValidSignal;
}
@end