Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 926
iyuna Avatar asked Apr 18 '17 10:04

iyuna


2 Answers

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)
    }
}
like image 121
jjoelson Avatar answered Nov 19 '22 22:11

jjoelson


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>
like image 45
Alistra Avatar answered Nov 19 '22 21:11

Alistra