Created
August 7, 2021 15:52
-
-
Save fishkingsin/8ebba693b4de116304497db90eda27ea to your computer and use it in GitHub Desktop.
Two Stream Solution
This file contains 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
import RxSwift | |
import RxCocoa | |
//func ignoreNil<A>(x: A?) -> Observable<A> { | |
// return x.map { Observable.just($0) } ?? Observable.empty() | |
//} | |
func ignoreNil<A>(x: A?) -> Driver<A> { | |
return x.map { Driver.just($0) } ?? Driver.empty() | |
} | |
func allContainValue<A, B, C>(_ a: A?, _ b: B?, _ c: C?) -> Bool { | |
a != nil && b != nil && c != nil | |
} | |
class Parent { | |
let bag = DisposeBag() | |
let streamA: BehaviorRelay<String?> = BehaviorRelay(value: nil) | |
let streamB: BehaviorRelay<String?> = BehaviorRelay(value: nil) | |
let dummyStream: BehaviorRelay<String?> = BehaviorRelay(value: nil) | |
var moduleVisibility: BehaviorRelay<Bool?> = BehaviorRelay(value: nil) | |
init() { | |
BehaviorRelay | |
.combineLatest( | |
streamA | |
.flatMap(ignoreNil) | |
.distinctUntilChanged(), | |
streamB | |
.flatMap(ignoreNil) | |
.distinctUntilChanged(), | |
dummyStream | |
.flatMap(ignoreNil) | |
.distinctUntilChanged() | |
) | |
.compactMap{ allContainValue($0.0, $0.1, $0.2) ? ($0.0!, $0.1!, $0.2!) : nil } | |
.observe(on: MainScheduler.instance) | |
.subscribe (onNext: {[weak self ] a, b, c in | |
guard let self = self else { return } | |
print("moduleVisibility \(a) \(b) \(c)") | |
self.moduleVisibility.accept(true) | |
}).disposed(by: bag) | |
} | |
} | |
class Child: Parent { | |
override init() { | |
super.init() | |
moduleVisibility | |
.flatMap(ignoreNil) | |
.asObservable() | |
.filter({ $0 == true}) | |
.withLatestFrom( | |
BehaviorRelay | |
.combineLatest( | |
streamA | |
.flatMap(ignoreNil) | |
.distinctUntilChanged(), | |
streamB | |
.flatMap(ignoreNil) | |
.distinctUntilChanged(), | |
dummyStream | |
.flatMap(ignoreNil) | |
.distinctUntilChanged() | |
) | |
.compactMap{ allContainValue($0.0, $0.1, $0.2) ? ($0.0!, $0.1!, $0.2!) : nil } | |
) | |
.observe(on: MainScheduler.instance) | |
.subscribe(onNext: { [weak self ] a, b, c in | |
guard let self = self else { return } | |
// This line does not get called | |
print("combineStream \(a) \(b) \(c)") | |
self.moduleVisibility.accept(nil) | |
self.streamA.accept(nil) | |
self.streamB.accept(nil) | |
self.dummyStream.accept(nil) | |
}).disposed(by: bag) | |
} | |
} | |
var child: Child? = Child() | |
child?.streamA.accept("A") | |
child?.streamB.accept("B") | |
child?.dummyStream.accept("C") | |
child?.streamA.accept("E") | |
child?.streamB.accept("F") | |
child?.dummyStream.accept("G") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment