Skip to content

Instantly share code, notes, and snippets.

@saru2020
Last active August 20, 2019 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save saru2020/8371552ede7c355e0df045124350d39b to your computer and use it in GitHub Desktop.
Save saru2020/8371552ede7c355e0df045124350d39b to your computer and use it in GitHub Desktop.
let disposeBag = DisposeBag()
//1
let behaviourRelay = BehaviorRelay<String>(value: "")
//2
let subscription1 = behaviourRelay.subscribe(onNext:{ string in
print("subscription1: ", string)
})
//3
subscription1.disposed(by: disposeBag)
//4
// subscription1 receives these 2 events, subscription2 won't
behaviourRelay.accept("Hey")
behaviourRelay.accept("there")
//5
// subscription2 will not get "Hey" because it susbcribed later but "there" will be received as it was the last event
let subscription2 = behaviourRelay.subscribe(onNext:{ string in
print("subscription2: ", string)
})
//6
subscription2.disposed(by: disposeBag)
//7
behaviourRelay.accept("Both Subscriptions receive this message")
Result:
subscription1:
subscription1: Hey
subscription1: there
subscription2: there
subscription1: Both Subscriptions receive this message
subscription2: Both Subscriptions receive this message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment