Skip to content

Commit

Permalink
Merge pull request #155 from ReactiveCocoa/action-retaining
Browse files Browse the repository at this point in the history
Make `Action` retain its state property.
  • Loading branch information
mdiep authored Dec 15, 2016
2 parents 0f2fc54 + 4c0d805 commit 253a8d9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Sources/Action.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ public final class Action<Input, Output, Error: Swift.Error> {
public init<State: PropertyProtocol>(state property: State, enabledIf isEnabled: @escaping (State.Value) -> Bool, _ execute: @escaping (State.Value, Input) -> SignalProducer<Output, Error>) {
deinitToken = Lifetime.Token()
lifetime = Lifetime(deinitToken)

// Retain the `property` for the created `Action`.
lifetime.ended.observeCompleted { _ = property }

executeClosure = { state, input in execute(state as! State.Value, input) }

Expand Down
20 changes: 20 additions & 0 deletions Tests/ReactiveSwiftTests/ActionSpec.swift
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,26 @@ class ActionSpec: QuickSpec {
action.errors.observeValues { errors.append($0) }
action.completed.observeValues { completedCount += 1 }
}

it("should retain the state property") {
var property: MutableProperty<Bool>? = MutableProperty(false)
weak var weakProperty = property

var action: Action<(), (), NoError>? = Action(state: property!, enabledIf: { _ in true }) { _ in
return .empty
}

expect(weakProperty).toNot(beNil())

property = nil
expect(weakProperty).toNot(beNil())

action = nil
expect(weakProperty).to(beNil())

// Mute "unused variable" warning.
_ = action
}

it("should be disabled and not executing after initialization") {
expect(action.isEnabled.value) == false
Expand Down

0 comments on commit 253a8d9

Please sign in to comment.