RxSwift: share()-ing is Caring

Shai Mishali
Jan 16 · 6 min read

A simple network request mapped to a name and phone when user taps a button
Bind your View Model’s output to your UI layer
Overview of a user’s tap processed by a ViewModel into a name & phone, via an API Service
Each subscriber gets their own resource — and invokes the initial stream individually on each emission
Further branch the original stream by creating additional mappings
More mappings? More resources! Still individual and separated

share() to the rescue!

Fortunately, an extremely useful operator called share() exists to solve this specific issue!

share() shares the stream’s resources among its subscribers
The stream is shared among all of its subscribers
getUniqueId without resource sharing
getUniqueId with resource sharing

Going deeper

You used the share operator in its most basic form, e.g. — share(), But there’s much more to know when you look into the full signature of this operator.

share(replay:scope:) — the full signature

Replay

The replay count argument is quite self-explanatory. It basically means “How many elements would you like me to replay to new subscribers?”.

share(replay:) with various replay values

Scope

The scope argument has two possible values: .whileConnected (the default), and .forever.

  • .forever: The internal cache of the stream is not cleared, even after the number of subscribers drops from 1 to 0. Meaning, future subscribers could potentially get stale events from the internal cache of the shared stream. It’s not recommended using operators such as retry in this case, as the retry might “carry” stale events and cause unexpected behavior.
On the left side — a stream shared with a .whileConnected scope. On the right side — a stream shared with the .forever scope.

Shared Sequences are your (and your app’s) friends

RxCocoa, the Cocoa-specific companion library that’s part of the RxSwift project, contains a concept called a Shared Sequence. These are simply helper traits that already have some specific sharing behavior attached to them, by conforming to the SharingStrategyProtocol protocol.

Driver and Signal — RxCocoa’a Shared Sequences

Gett Engineering

Code, stories, tips, thoughts, experimentations from the day-to-day work of our R&D team.

Shai Mishali

Written by

iOS Tech Lead @ Gett 🚕 RxSwift & RxSwiftCommunity core contributor. International speaker and worldwide hackathon winner. Fiddling with tech for a living. 🤓

Gett Engineering

Code, stories, tips, thoughts, experimentations from the day-to-day work of our R&D team.