RACBehaviorSubject.m 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. //
  2. // RACBehaviorSubject.m
  3. // ReactiveObjC
  4. //
  5. // Created by Josh Abernathy on 3/16/12.
  6. // Copyright (c) 2012 GitHub, Inc. All rights reserved.
  7. //
  8. #import "RACBehaviorSubject.h"
  9. #import "RACDisposable.h"
  10. #import "RACScheduler+Private.h"
  11. @interface RACBehaviorSubject<ValueType> ()
  12. // This property should only be used while synchronized on self.
  13. @property (nonatomic, strong) ValueType currentValue;
  14. @end
  15. @implementation RACBehaviorSubject
  16. #pragma mark Lifecycle
  17. + (instancetype)behaviorSubjectWithDefaultValue:(id)value {
  18. RACBehaviorSubject *subject = [self subject];
  19. subject.currentValue = value;
  20. return subject;
  21. }
  22. #pragma mark RACSignal
  23. - (RACDisposable *)subscribe:(id<RACSubscriber>)subscriber {
  24. RACDisposable *subscriptionDisposable = [super subscribe:subscriber];
  25. RACDisposable *schedulingDisposable = [RACScheduler.subscriptionScheduler schedule:^{
  26. @synchronized (self) {
  27. [subscriber sendNext:self.currentValue];
  28. }
  29. }];
  30. return [RACDisposable disposableWithBlock:^{
  31. [subscriptionDisposable dispose];
  32. [schedulingDisposable dispose];
  33. }];
  34. }
  35. #pragma mark RACSubscriber
  36. - (void)sendNext:(id)value {
  37. @synchronized (self) {
  38. self.currentValue = value;
  39. [super sendNext:value];
  40. }
  41. }
  42. @end