Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
SRGLoadableViewModel
@class RACSignal;
@interface SRGLoadableViewModel : NSObject
@property (nonatomic) BOOL loading;
@property (nonatomic) NSError *lastError;
@property (nonatomic) id result;
@property (nonatomic) RACSignal *computationSignal;
@end
#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