Skip to content

Instantly share code, notes, and snippets.

@ibrahimkteish
Last active February 1, 2018 14:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ibrahimkteish/b5b2f53f03902017ed2af9809c25f305 to your computer and use it in GitHub Desktop.
Save ibrahimkteish/b5b2f53f03902017ed2af9809c25f305 to your computer and use it in GitHub Desktop.
RxSwift PublishSubject type
//disposeBag from memoy management
let disposeBag = DisposeBag()
//Create our PublishSubject with a string type
let subject = PublishSubject<String>()
//ErrorType will be used for emitting an Error event
enum Error: ErrorType {
case Test
}
//emit our first event before any subscription to the subject
subject.on(.Next("Bob"))
//New Subscription
subject.subscribe {
print($0)
}
.addDisposableTo(disposeBag)
//emits
subject.on(.Next("Hello"))
subject.onNext("World") //onNext is a Convenience method equivalent to on(.Next(element: E))
//New Subscription
let secondSubscription = subject.subscribe {
print("second subscription:", $0)
}
//add it to the disposeBag
secondSubscription.addDisposableTo(disposeBag)
//emit
subject.onNext("Ibrahim")
//dispose our second subscriber
secondSubscription.dispose()
//emit
subject.onNext("After disposing the second subscriber")
//emit an Error event
subject.onError(Error.Test) // or subject.onCompleted()
//New Subscription
let ThirdSubscription = subject.subscribe {
print("third subscription:", $0)
}
//add it to the disposeBag
ThirdSubscription.addDisposableTo(disposeBag)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment