Created
February 1, 2023 10:50
-
-
Save toshi0383/6595051f8902d66bdb77b189aeb58615 to your computer and use it in GitHub Desktop.
ValveProperty #CodePiece
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 弁(Valve)のように値がこなくなったら自動的に元の値に戻るProperty。 | |
/// 元に戻る時間も指定できる。 | |
@propertyWrapper | |
struct ValveProperty<Value> { | |
private let relay: BehaviorRelay<Value> | |
private let property: Property<Value> | |
init( | |
automaticallyTogglesToInitialValue initialValue: Value, | |
afterInterval interval: RxTimeInterval = .milliseconds(1000), | |
scheduler: SchedulerType = ConcurrentMainScheduler.instance | |
) { | |
relay = .init(value: initialValue) | |
property = Property( | |
unsafeObservable: relay.asObservable() | |
.flatMapLatest { | |
Observable.just($0) | |
.concat( | |
Observable.just(initialValue) | |
.delay(interval, scheduler: scheduler) | |
) | |
} | |
) | |
} | |
var wrappedValue: Property<Value> { | |
property | |
} | |
var projectedValue: BehaviorRelay<Value> { | |
relay | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment