Skip to content

Instantly share code, notes, and snippets.

@toshi0383
Created February 1, 2023 10:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toshi0383/6595051f8902d66bdb77b189aeb58615 to your computer and use it in GitHub Desktop.
Save toshi0383/6595051f8902d66bdb77b189aeb58615 to your computer and use it in GitHub Desktop.
ValveProperty #CodePiece
/// 弁(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