UIRefreshControl+RACCommandSupport.m 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. //
  2. // UIRefreshControl+RACCommandSupport.m
  3. // ReactiveCocoa
  4. //
  5. // Created by Dave Lee on 2013-10-17.
  6. // Copyright (c) 2013 GitHub, Inc. All rights reserved.
  7. //
  8. #import "UIRefreshControl+RACCommandSupport.h"
  9. #import "RACEXTKeyPathCoding.h"
  10. #import "NSObject+RACSelectorSignal.h"
  11. #import "RACDisposable.h"
  12. #import "RACCommand.h"
  13. #import "RACCompoundDisposable.h"
  14. #import "RACSignal.h"
  15. #import "RACSignal+Operations.h"
  16. #import "UIControl+RACSignalSupport.h"
  17. #import <objc/runtime.h>
  18. static void *UIRefreshControlRACCommandKey = &UIRefreshControlRACCommandKey;
  19. static void *UIRefreshControlDisposableKey = &UIRefreshControlDisposableKey;
  20. @implementation UIRefreshControl (RACCommandSupport)
  21. - (RACCommand *)rac_command {
  22. return objc_getAssociatedObject(self, UIRefreshControlRACCommandKey);
  23. }
  24. - (void)setRac_command:(RACCommand *)command {
  25. objc_setAssociatedObject(self, UIRefreshControlRACCommandKey, command, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  26. // Dispose of any active command associations.
  27. [objc_getAssociatedObject(self, UIRefreshControlDisposableKey) dispose];
  28. if (command == nil) return;
  29. // Like RAC(self, enabled) = command.enabled; but with access to disposable.
  30. RACDisposable *enabledDisposable = [command.enabled setKeyPath:@keypath(self.enabled) onObject:self];
  31. RACDisposable *executionDisposable = [[[[self
  32. rac_signalForControlEvents:UIControlEventValueChanged]
  33. map:^(UIRefreshControl *x) {
  34. return [[[command
  35. execute:x]
  36. catchTo:[RACSignal empty]]
  37. then:^{
  38. return [RACSignal return:x];
  39. }];
  40. }]
  41. concat]
  42. subscribeNext:^(UIRefreshControl *x) {
  43. [x endRefreshing];
  44. }];
  45. RACDisposable *commandDisposable = [RACCompoundDisposable compoundDisposableWithDisposables:@[ enabledDisposable, executionDisposable ]];
  46. objc_setAssociatedObject(self, UIRefreshControlDisposableKey, commandDisposable, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  47. }
  48. @end