-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
Copy pathBehaviorRelay.swift
44 lines (36 loc) · 1.22 KB
/
BehaviorRelay.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//
// BehaviorRelay.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 10/7/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
import RxSwift
/// BehaviorRelay is a wrapper for `BehaviorSubject`.
///
/// Unlike `BehaviorSubject` it can't terminate with error or completed.
public final class BehaviorRelay<Element>: ObservableType {
public typealias E = Element
private let _subject: BehaviorSubject<Element>
/// Accepts `event` and emits it to subscribers
public func accept(_ event: Element) {
_subject.onNext(event)
}
/// Current value of behavior subject
public var value: Element {
// this try! is ok because subject can't error out or be disposed
return try! _subject.value()
}
/// Initializes behavior relay with initial value.
public init(value: Element) {
_subject = BehaviorSubject(value: value)
}
/// Subscribes observer
public func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E {
return _subject.subscribe(observer)
}
/// - returns: Canonical interface for push style sequence
public func asObservable() -> Observable<Element> {
return _subject.asObservable()
}
}