-
-
Save gavrix/1e09f68871519818401d to your computer and use it in GitHub Desktop.
SRGLoadableViewModel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@class RACSignal; | |
@interface SRGLoadableViewModel : NSObject | |
@property (nonatomic) BOOL loading; | |
@property (nonatomic) NSError *lastError; | |
@property (nonatomic) id result; | |
@property (nonatomic) RACSignal *computationSignal; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "SRGLoadableViewModel.h" | |
#import <ReactiveCocoa/ReactiveCocoa.h> | |
@implementation SRGLoadableViewModel | |
- (instancetype)init { | |
self = [super init]; | |
if (self) { | |
RACSignal *loadableSignal = [[RACObserve(self, computationSignal) | |
map: ^id (RACSignal *signal) { | |
return signal ?: RACSignal.empty; | |
}] map: ^id (RACSignal *loadingSignal) { | |
return loadingSignal.replayLazily; | |
}].replayLast; | |
RAC(self, lastError) = [loadableSignal map:^id(RACSignal *signal) { | |
return [[signal.ignoreValues.materialize filter:^BOOL(RACEvent *event) { | |
return event.eventType == RACEventTypeError; | |
}] map:^id(RACEvent *event) { | |
return event.error; | |
}]; | |
}].switchToLatest; | |
RAC(self, result) = [loadableSignal map:^id(RACSignal *signal) { | |
return [signal catchTo:[RACSignal return:nil]]; | |
}].switchToLatest; | |
RAC(self, loading) = [loadableSignal map:^id(RACSignal *signal) { | |
return [RACSignal concat:@[ | |
[RACSignal return:@YES], | |
[signal.ignoreValues catchTo:RACSignal.empty], | |
[RACSignal return:@NO] | |
]]; | |
}].switchToLatest; | |
} | |
return self; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment