0

When fetching data, most people use PublishSubject, but what happens when they use PublishRelay? If an error occurs in the PublishSubject while using the app, isn't it dangerous because the app dies?

Seul
  • 47
  • 3
  • What led you to believe that "most people" use PublishSubjects for fetching data? Doing so is a horrible idea. – Daniel T. May 01 '22 at 11:40
  • https://github.com/iamchiwon/RxSwift_In_4_Hours/blob/master/Example/season2/step3%2BRx%2BMVVM/RxSwift%2BMVVM/ViewModel/MenuViewModel.swift Because I'm making an app referring to the structure of this code. In this code, the View gave an event to the ViewModel's PublishSubject.asObserver. My question was, "Can't we change all PulishSubjects to PublishRelay in this code?" If this code itself is wrong, I would appreciate it if you could advice me. – Seul May 01 '22 at 14:13
  • In my opinion this code is a very poor example of Rx. There is way too much boilerplate needed and the one class is trying to do way too much work. A well written view model will not need any subjects or a dispose bag for that matter. It should be Observables in, Observables out. Check out some of my examples instead: https://github.com/danielt1263 – Daniel T. May 01 '22 at 15:21
  • I reworked the example you provided. Here's how it *should* be written. https://gist.github.com/danielt1263/bb1af5f2864b2ee788c129deb5f48be2 – Daniel T. May 02 '22 at 11:39

1 Answers1

0

You shouldn't be using either when fetching data.

Subjects [and Relays] provide a convenient way to poke around Rx, however they are not recommended for day to day use... Instead of using subjects, favor the factory methods.

The Observable interface is the dominant type that you will be exposed to for representing a sequence of data in motion, and therefore will comprise the core concern for most of your work with Rx...

Avoid the use of the subject types [including Relays]. Rx is effectively a functional programming paradigm. Using subjects means we are now managing state, which is potentially mutating. Dealing with both mutating state and asynchronous programming at the same time is very hard to get right. Furthermore, many of the operators (extension methods) have been carefully written to ensure that correct and consistent lifetime of subscriptions and sequences is maintained; when you introduce subjects, you can break this.

-- Introduction to Rx

Note that URLSession.shared.rx.data(request:) returns an Observable, not a Subject or Relay.

Daniel T.
  • 32,821
  • 6
  • 50
  • 72
  • If I have to remove a specific post or change the contents of the post without refetching, should I accept it again after changing the post of a specific IndexPath using Behavior Relay? – Seul May 23 '22 at 12:05
  • This might require a separate question. The contents of the behavior relay should be a struct or enum, not a class. The only way to change the contents of the relay is to call accept. – Daniel T. May 23 '22 at 12:08