15

I am new to RxSwift programming. I am confused between the two while coding. Which one should be used to store datasource of table and how to decide that ?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Emtiyaj Ali
  • 180
  • 1
  • 6
  • 13

2 Answers2

15
  • A PublishSubject can emit an error or completed event while a PublishRelay cannot.
  • A PublishSubject conforms to the ObserverType protocol while the PublishRelay does not.

Another important point that was alluded to by @RobMayoff in his comment. Neither a PublishSubject nor a PublishRelay stores state, so neither of them are a good idea to "store datasource of table".

Fortunately, you don't need to store the state yourself because the DataSource object that the items operator creates internally stores it.

In other words, you don't need to use a Subject or Relay (of any sort) to feed a table view. Just use an Observable.

Daniel T.
  • 32,821
  • 6
  • 50
  • 72
0

If you look at the interface to PublishRelay you can see that it wraps a PublishSubject but it hides this from its interface. So you can only send it accept(_ event: Element) which means you cannot send it error or completed Events only next elements.

    public final class PublishRelay<Element>: ObservableType {
    private let subject: PublishSubject<Element>
    
    // Accepts `event` and emits it to subscribers
    public func accept(_ event: Element) {
        self.subject.onNext(event)
    }
    
    /// Initializes with internal empty subject.
    public init() {
        self.subject = PublishSubject()
    }

    //...
}

Anyhow, if you look at examples of tableview using RxCocoa they just wrap an array as an Observable usually using Just or create that you then pass to the tableview using RxCocoa's interface. You don't really want a Subject just a plain observable.

SmileBot
  • 19,393
  • 7
  • 65
  • 62