RxSwift — Pass data using Publish Subject

Jaydeep Vora
3 min readJun 15, 2018

--

There many peoples describing the different definitions of Reactive programming. but as per my research and analysis, I had found a short line for this.

“RxSwift is a new paradigm for asynchronous programming.,

I had been working with RxSwift for the last year, So I had an idea about its benefits. I was able to answer those questions vaguely. I failed to be concise though.

Notify parent controller about data changes:

The first thing is creating an Outlet of UILabel in ViewController.swift file with default text and DisposeBag variable. DisposeBag is a memory management mechanism of RxSwift.

Declare variable

Now, We write code for subscribing which observes the value of EditViewController text and color’s PublishSubject. PublishSubject is one of the types of Subjects. We can say that PublishSubject is both Observer and input.

But as per different subject properties, PublishSubject ignores all elements that were emitted before subscribing.

We have one Button in ViewController called Let’s Edit which redirects t EditViewController to choose text and color. Below is the code for the button.

Subscribe the observer:

In the above code, we observe the text and color subject emitted by EditViewController when clicking on the red, green or blue button. this can be done using subscribe(onNext, onError, onCompleted) method. subscribe method will be canceled by disposed(by:) method.

onNext() will emit the value in the below code and that value will be subscribed by ViewController simply.

Declaring Publish subject:

Here we create the one text field outlet. Also, declare text and color Observer.
text observer is a type of String that passes the value of text field and color observer pass the color object as per clicked on color buttons (red, blue & green).

Emit element through observer:

When the user enters some text on the text field and touches on one of the color buttons below process is happened

  1. textObserver emit the text value.
  2. As per the color button tag, it will pass the color value using colorObserver
  3. And at last step, it’ll pop to ViewController, so changes can appear.

the demo program output is below. you can check how it is simple & you can also try with your code.

Enjoy code…

--

--

Jaydeep Vora
Jaydeep Vora

Written by Jaydeep Vora

iOS | Swift | Flutter | SwiftUI, Let’s grow together | LinkedIn — https://www.linkedin.com/in/jaydeep-vora | Skype — jaydeep.33

No responses yet