UIRefreshControl+RACCommandSupport.m 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. //
  2. // UIRefreshControl+RACCommandSupport.m
  3. // ReactiveObjC
  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 <ReactiveObjC/RACEXTKeyPathCoding.h>
  10. #import "RACCommand.h"
  11. #import "RACCompoundDisposable.h"
  12. #import "RACDisposable.h"
  13. #import "RACSignal.h"
  14. #import "RACSignal+Operations.h"
  15. #import "UIControl+RACSignalSupport.h"
  16. #import <objc/runtime.h>
  17. static void *UIRefreshControlRACCommandKey = &UIRefreshControlRACCommandKey;
  18. static void *UIRefreshControlDisposableKey = &UIRefreshControlDisposableKey;
  19. @implementation UIRefreshControl (RACCommandSupport)
  20. - (RACCommand *)rac_command {
  21. return objc_getAssociatedObject(self, UIRefreshControlRACCommandKey);
  22. }
  23. - (void)setRac_command:(RACCommand *)command {
  24. objc_setAssociatedObject(self, UIRefreshControlRACCommandKey, command, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  25. // Dispose of any active command associations.
  26. [objc_getAssociatedObject(self, UIRefreshControlDisposableKey) dispose];
  27. if (command == nil) return;
  28. // Like RAC(self, enabled) = command.enabled; but with access to disposable.
  29. RACDisposable *enabledDisposable = [command.enabled setKeyPath:@keypath(self.enabled) onObject:self];
  30. RACDisposable *executionDisposable = [[[[[self
  31. rac_signalForControlEvents:UIControlEventValueChanged]
  32. map:^(UIRefreshControl *x) {
  33. return [[[command
  34. execute:x]
  35. catchTo:[RACSignal empty]]
  36. then:^{
  37. return [RACSignal return:x];
  38. }];
  39. }]
  40. concat]
  41. deliverOnMainThread]
  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