My RxSwift Summary ⑤ (What is Subjects / Relay?)

This article is My RxSwift Summary ①, My RxSwift Summary ②, My RxSwift Summary ③ (What is Observable? --Part 1), [My RxSwift Summary ④ (What is disposebag?)](Https: //qiita.com/Masa_asaM/items/0b1196940cb3f5fcfe0b) is a continuation.

What is Subject?

Subject works as both ʻobserver and ʻobservable. It can receive events, process them, and generate events. ..

PublishSubject PublishSubject is aSubject that starts with no initial value and tells subscriber only the newly released elements after subscribe. (However, completed / ʻerror is also transmitted to subscriberwhosubscribe` after being released.) As shown in the marble diagram, image.png Becomes Also, if you express the marble diagram in code,

PublishSubject.swift


let publishSubject = PublishSubject<String>()
publishSubject.onNext("1")
let subscriber1 = publishSubject
    .subscribe{ event in
        print("subscriber1:" , event.element ?? event)
}
publishSubject.onNext("2")
let subscriber2 = publishSubject
    .subscribe{ event in
        print("subscriber2:" , event.element ?? event)
}
publishSubject.onNext("3")
publishSubject.onCompleted()
let subscriber3 = publishSubject
    .subscribe{ event in
        print("subscriber3:" , event.element ?? event)
}

output


subscriber1: 2
subscriber1: 3
subscriber2: 3
subscriber1: completed
subscriber2: completed
subscriber3: completed

Will be.

When is it used?

Since PublishSubject is convenient when notifying subscriber of a new event, it is used for updating according to the user's click. In addition, since it is excellent in real time, it can be applied to chats and the like where frequent exchanges are performed.

BehaviorSubject Behavior Subject is Publish Subject with the concept of replay (= transmitting the latest event to subscriber). Therefore, if there is no initial value, replay cannot be performed and an error will occur. It is essential to have an initial value or to define ʻelement as ʻoptional.

As shown in the marble diagram, image.png Will be. Also, if you express the marble diagram in code,

BehaviorSubject.swift


let behaviorSubject = BehaviorSubject<String>(value: "1")
let subscriber1 = behaviorSubject
    .subscribe{ event in
        print("subscriber1:" , event.element ?? event)
}
behaviorSubject.onNext("2")
let subscriber2 = behaviorSubject
    .subscribe{ event in
        print("subscriber2:" , event.element ?? event)
}
behaviorSubject.onNext("3")
behaviorSubject.onCompleted()
let subscriber3 = behaviorSubject
    .subscribe{ event in
        print("subscriber3:" , event.element ?? event)
}

output


subscriber1: 1
subscriber1: 2
subscriber2: 2
subscriber1: 3
subscriber2: 3
subscriber1: completed
subscriber2: completed
subscriber3: completed

When is it used?

Since BehaviorSubject can show the latest state of Subject in the view, it is used in situations such as putting the latest value in placeholder in advance or showing an indicator during loading.

ReplaySubject With BehaviorSubject, only the latest event could be transmitted to subscriber, but with ReplaySubject, the number of events specified in the buffer size can be transmitted. However, if you increase the buffer size or use too much data size such as an image, it may cause memory tightness, so be careful. As shown in the marble diagram, image.png Becomes Also, if you express the marble diagram in code,

ReplaySubject.swift


let replaySubject = ReplaySubject<String>.create(bufferSize: 2)
replaySubject.onNext("1")
replaySubject.onNext("2")
let subscriber1 = replaySubject
    .subscribe { event in
        print("subscriber1:", event.element ?? event)
}
replaySubject.onNext("3")

output


subscriber1: 1
subscriber1: 2
subscriber1: 3

Will be.

When is it used?

It is used when you want to take a difference from the previous one.

AsyncSubject ʻAsyncSubject passes the last value to subscriberimmediately aftercompleted` is played. As shown in the marble diagram, image.png Will be.

Expressing this in code,

AsyncSubject.swift


let asyncSubject = AsyncSubject<String>()
asyncSubject.onNext("1")
let subscriber1 = asyncSubject
    .subscribe { event in
        print("subscriber1:", event.element ?? event)
}
asyncSubject.onNext("2")
let subscriber2 = asyncSubject
    .subscribe { event in
        print("subscriber2:", event.element ?? event)
}
asyncSubject.onNext("3")
asyncSubject.onCompleted()

output


subscriber1: 3
subscriber2: 3
subscriber1: completed
subscriber2: completed

Will be.

When is it used?

Useful when receiving API callbacks

What is Relay?

Relay is the [wrapper] of subjects (https://qiita.com/dsudo/items/51ca822169ef9f8b9bc3). Its role as a wrapper is to not accept ʻerror or completed, but to pass only the element that flows in next with ʻaccept (_ :).

Publish Relay corresponds to Publish Subject, and Behavior Relay corresponds to Behavior Subject. The code shows the following, respectively.

PublishRelay.swift


let publishRelay = PublishRelay<String>()

let disposeBag = DisposeBag()
publishRelay.accept("1")
publishRelay
    .subscribe(onNext: {
        print($0)
    })
    .disposed(by: disposeBag)

publishRelay.accept("2")

output


2

BehaviorRelay.swift


let behaviorRelay = BehaviorRelay(value: "Initial value")
let disposeBag = DisposeBag()

behaviorRelay.accept("1")

behaviorRelay
    .subscribe {
        print("subscriber1:" , $0.element ?? $0)
}
.disposed(by: disposeBag)

behaviorRelay.accept("2")

behaviorRelay
    .subscribe {
        print("subscriber2:", $0.element ?? $0)
}
.disposed(by: disposeBag)

behaviorRelay.accept("3")

output


subscriber1: 1
subscriber1: 2
subscriber2: 2
subscriber1: 3
subscriber2: 3

Will be.

Recommended Posts

My RxSwift Summary ⑤ (What is Subjects / Relay?)
My RxSwift Summary ③ (What is Observable?)
My RxSwift Summary ④ (What is dispose bag?)
My RxSwift Summary ②
My RxSwift Summary ①
What is Java Assertion? Summary.
What is Cubby
What is Docker?
What is null? ]
What is java
What is Keycloak
What is maven?
What is Jackson?
What is Docker
What is self
What is Jenkins
What is ArgumentMatcher?
What is IM-Juggling?
What is params
What is SLF4J?
What is Facade? ??
What is Java <>?
What is Gradle?
What is POJO
What is Java
What is centOS
What is RubyGem?
What is programming?
What is before_action?
What is Docker
What is Byte?
What is Tomcat
What is Maven Assembly?
What is `docker-compose up`?
What is a constructor?
What is vue cli
What is an interface?
What is Ruby's self?
What is hard coding?
What is a stream
What is Ruby's attr_accessor?
What is Java Encapsulation?
What is permission denied?
What is instance control?
What is an initializer?
What is Spring Tools 4
What is an operator?
What is object orientation?
What is Guava's @VisibleForTesting?
What is MVC model?
What is an annotation?
What is Java technology?
What is Java API-java
What is @ (instance variable)?
What is Gradle's Artifact?
What is JPA Auditing?
[Swift] What is dismiss?
[Java] What is flatMap?
What is a Servlet?
What is web development?
[Java] What is JavaBeans?