iyuna
iyuna

Reputation: 1797

ReactiveSwift mutable property with read only public access

I have a class with enum property state. This property's value (by value I mean ReactiveSwift.Property's value) needs to be accessed and observed by other classes, but value change should be private. Currently it is implemented in a such way:

enum State {
    case stopped, running, paused
}

var state: Property<State> {
    return Property(mutableState)
}
fileprivate let mutableState = MutableProperty<State>(.stopped)

This pattern allows me to modify mutableState property within class file. At the same time outside the class state is available only for reading and observing.

The question is whether there is a way to implement a similar thing using single property? Also probably someone can suggest a better pattern for the same solution?

Upvotes: 5

Views: 1243

Answers (2)

jjoelson
jjoelson

Reputation: 5941

I can't think of any way to do this with a single property. The only adjustment I would make to your code is to make state a stored property rather than a computed property that gets newly created each time it is accessed:

class Foo {
    let state: Property<State>

    fileprivate let mutableState = MutableProperty<State>(.stopped)

    init() {
        state = Property(mutableState)
    }
}

Upvotes: 7

Alistra
Alistra

Reputation: 5195

Depending where you want to mutate the state, you can try doing either of:

private(set) var state: Property<State>

or if you modify it from an extension but still the same file

fileprivate(set) var state: Property<State>

Upvotes: 1

Related Questions