SlideShare a Scribd company logo
Combine Framework
2
Combine
A unified declarative API for processing values over time
SwiftUI:
1. @State
2. @Binding
3. @ObservedObject
Foundation:
1. Timer
2. NotificationCenter
3. URLSession
4. KVO
Core Data:
1. FetchedRequest
2. NSManagedObject
3
ReactiveSwift vs Combine
Rx ReactiveSwift Combine
Deployment target iOS 8+ iOS 8+ iOS 13+
Platform supported macOS, iOS, watchOS, tvOS, and
Linux
macOS, iOS, watchOS, tvOS, and
Linux.
macOS, iOS, watchOS, tvOS, and
UIKit for Mac.
Framework consumption Third-party Third-party First-party
Maintained by Open source Open source Apple
UI bind RxCocoa ReactiveCocoa SwiftUI
passwordTextField.rx.text.orEmpt
y .bind(to: viewModel.password)
.disposed(by: disposeBag)
testLabel.reactive.text <~
signal.take(duringLifetimeOf:
self)
publisher.assign(to: .text, on:
label)
Error Management
- + +
Backpressure
- - +
4
ReactiveSwift vs Combine
Combine ReactiveSwift
Publisher* Signal, SignalProducer
Subscriber* Observer
Value event:
value(Output)
Completion:
finished
failure(Error)
Value event:
value(Output)
Completion:
completed
failed(Error)
interrupted
5
Publishers
Emit values over time to one or more interested parties, such as subscribers.
Including operation: math calculations, networking or handling user events, every publisher can emit multiple events
types:
1. An output value of the publisher's generic Output type.
2. A successful completion.
3. A completion with an error of the publisher's Failure type.
A publisher can emitzero or morevalues but onlyone completion event, which can either be a normal completion event or an
error.
Once a publisher emits a completion event, it’s finished and can no longer emit any more events.
A publisher only emits an event when there’s at least one subscriber.
Summary:
1. describe how values and errors are produced.
2. value type
3. allow registration of a Subscriber
4. don’t emit values or perform work if they don’t have any subscribers (exeption Future)
6
Publishers
7
Publishers
Combine provides a number of additional convenience publishers:
● Just
● Empty
● De!ered
● Future
● Sequence
● ObservebleObjectPublisher
● @Publisher
● Fail
Just- a publisher that emits a single value to a subscriber and then complete.
Future- asynchronouslyproduce a single result and then complete. Executes immediately when it is created instead of waiting for a subsc
like a normal publisher does. They’re working with a Future that begins its execution immediately, emits a single value and re-emits the
value to its subscribers if it receives more than a single subscriber. Reference type.
De!eredallows to change from Future<Int, Never> to Deferred<Future<Int, Never>>. And than we have:
● The publisher will not perform work until it has subscribers
● If you subscribe to the same instance of this publisher more than once, the work will be repeated
Emptypublisher type can be used to create a publisher that immediately emits a .finished completion event.
Combine vs ReactiveSwift
Publisher
AnyPublisher
1. +
2. +
3. +
4. +
Future
1+, 2-, 3+, 4+, 5-
PassthroughSubject. / CurrentValueSubject
1-, 2+, 3-, 4+, 5+
SignalProducer
1. Signal producers start work on demand by
creating signals
2. Each produced signal may send di!erent
events at di!erent times
3. Disposing of a produced signal will interrupt it
4. Need to have a least one observer
Signal
1. Signals start work when instantiated
2. Observing a signal does not have side e!ects
3. All observers of a signal see the same events
in the same order
4. Terminating events dispose of signal
resources
5. Has manually controlled signal
(let (signal, observer) = Signal<Int, Never>.pipe())
8
Combine vs ReactiveSwift
CurrentValueSubject
MutableProperty
9
Observable boxes that always holds a value. This is a variables that can be observed for their changes.
Subscribers
10
Responsible for requesting data and accepting the data (and possible failures) provided by a publisher.
Initiates the request for data, and controls the amount of data it receives.
Described with two associated types, one for Input and one for Failure.
Summary:
● receives values and a completion
● reference type
Subscribers
11
Subscription
12
Subscription represents a connection between a publisher and subscriber.
Subscription allows:
● cancel subscription
● backpressure
Combine
13
Publisher
OutputType
FailureType
Subscriber
InputType
FailureType
Matching
14
Combine vs ReactiveSwiftObservation
Combine vs ReactiveSwift
15
ReactiveSwift
Combine
Subjects
16
Special case of publisher that also adhere to the subject protocol.
This protocol requires subjects to have a.send() method to allow the developer to send specific values
to a subscriber (or pipeline).
Subjects can be used to "inject" values into a stream, by calling the subject’s .send() method.
A subject will not signal for demand to its connected publishers until it has received at least one subscriber.
itself. When it receives any demand, it then signals for unlimited demand to connected publishers.
There are two types:
1. CurrentValueSubject
2. PassthroughSubject.
Subjects
17
Backpressure
18
Backpressure resolves around strategies to deal with Publishers that emit too many values, too rapidly
Situation: publisher emits 10000 values per second.
Life cycle
19
● When the subscriber is attached to a publisher, it starts with a call to.subscribe(Subscriber).
● The publisher in turn acknowledges the subscription callingreceive(subscription).
● After the subscription has been acknowledged, the subscriber requestsNvalues withrequest(_ : Demand).
● The publisher may then (as it has values) sendingN(or fewer)values: receive(_ : Input). A publisher should never sendmore
than the demand requested.
Also after the subscription has been
acknowledged, the subscriber can send
cancellation with.cancel().A publisher may
optionally sendcompletion:
receive(completion:).A completion can be
either a normal termination, or may be a
.failure completion, optionally propogat
an error type.
A pipeline that has been cancelled will n
send any completions.
Operators
20
Combine provides two built-in subscribers, which make working with data streams straightforward:
1. Thesinksubscriber allows you to provide closures with your code that will receive output values and com
From there, you can do anything your heart desires with the received events.
2. Theassignsubscriber allows you to, without the need of custom code,bindthe resulting output to some property
on your data model or on a UI control to display the data directly on-screen via a key path.
Operators
21
An object that acts both like a subscriber and a publisher.
Operators are classes that adopt both the Subscriber protocol and Publisher protocol.
They support subscribing to a publisher, and sending results to any subscribers.
You can create chains of these together, for processing, reacting, and transforming the data provided by a publish
requested by the subscriber.
22
OperatorsMap
● map<T>(_:)
● map<T0, T1>(_:_:)
● map<T0, T1, T2>(_:_:_:)
23
OperatorstryMap
The map operator allows for any combination of Output and Failure type and passes them through.
tryMap accepts any Input, Failure types, and allows any Output type, but will always output an <Error>
failure type.
24
Operators
flatMap It uses when you want to reach into inner
publisher to get its elements
25
Operators
flatMap
26
Operators
replaceNil/error/empty
27
Operators
Scan
28
Operators
removeDublicates
29
Operators
ignoreOutput
30
Operators
Drop
Imagine a scenario where you have a user tapping a button, but you want to ignore all taps until your isReady p
some result. This operator is perfect for this sort of condition.
31
Operators
Prefix
The prefix family of operators is similar to the drop family and provides prefix(_:), prefix(while:) and prefix(untilOu
However, instead of dropping values until some condition is met, the prefix operatorstakevalues until that condition is met.
32
Take -> First/drop/prefix
Operators
33
prepand
Operators
34
Append
Operators
35
switchToLatest
Operators
36
merge/combineLatest/zip
Operators
37
Operators
38
Operators
39
Operators
eraseToAnyPublisher
40
Error handle
Common operators you might want to try out:
● assertNoFailure (which will change the error type to Never and calls an assert
when an error occurs)
● mapError
● retry
● catch
● replaceError
41
Debugging
Fortunately, there are ways to debug in Combine with use of the following operators:
● Print ( to print log messages for all publishing events)
● Breakpoint ( which raises the debugger signal when a provided closure needs to stop the process in the
debugger)
● breakpointOnError (which only raises the
debugger upon receiving a failure)
● Timelane tool
(https://github.com/icanzilb/Timelane/rel
eases/tag/1.3) and add dependency to
project
https://github.com/icanzilb/TimelaneCo
mb
42
Combine in practice
Foundatio
n
43
Combine in practice
Disable button
44
Combine in practice
Periodically request
45
Wrapped request
46
Wrapped request
47
Combine in practice
Manually controlled publisher (like Signal<Input,
Error>.pipe()) and observe current value (like
MutableProperty)
48
Combine in practice
Sometimes it works
49
Combine in practice
TASK:Imagine that you want to make a single network call that multiple objects subscribe to without making
a new network call.
share()operator returns an instance of the Publishers.Share class. This new publisher “shares” the upstream
publisher. It will subscribe to the upstream publisher once, with the first incoming subscriber.
50
Combine in practice
TASK:Imagine that you want to make a single network call that multiple objects subscribe to without making
a new network call.
51
Combine in practice
TASK:Imagine that you want to make a single network call that multiple objects subscribe to without making a new
network call.
52
Combine in practice
TASK:Multiple requests using array ids
53
Combine in practice
TASK:Imagine that you want to make a single network call that multiple objects subscribe to without making
a new network call.
The reason for this is that the Future executed immediately,
and repeats its output. Reference type.
Wrapping a Future in Deferred makes it behave exactly the same
as any other Publisher
54
Combine in practice
Core Data fetch
55
Combine in practice
Schedulars
By default, several objects that you might be familiar with already conform to the Scheduler protocol:
1) RunLoop
2) DispatchQueue
3) OperationQueue
When you applyreceive(on:)to a publisher it will
make sure that all events are delivered downstream
on the scheduler you provide. Possition make sence.
Subscribe(on:)- specifies the scheduler on which to
perform subscribe, cancel, and request operations.
56
Combine in practice
Schedulars
57
Combine in practice
Schedulars
Background task
58
Background task (exeption URLSession)
59
A lot of publishers will emit values on the queue they received their subscriber on, but this is not always the case.
DataTaskPublisher is set up to publish its values o! the main thread at all ti
Multicast
60
A publisher conforming to ConnectablePublisher will have an additional mechanism to start the flow of
data after a subscriber has provided a request. This could be .autoconnect(), which will start the flow
of data as soon as a subscriber requests it. The other option is a separate .connect() call on the publisher itself.
KVO
61
KVO
62
63
List of references :
1. Combine framework
https://medium.com/flawless-app-stories/combine-framework-in-swift-b730ccde131
2. SwiftLeehttps://www.avanderlee.com/swift/combine/
3. Rx vs Combine
https://medium.com/gett-engineering/rxswift-to-apples-combine-cheat-sheet-e9ce
32b14c5b
4. Di!https://dzone.com/articles/combine-vs-rxswift-introduction-to-combine-amp-dif
5. Using Combine - Joseph Heck
6. Combine Asynchronous Programming with Swift_v1.0.2 By Scott Gardner, Shai Mishali,
Florent Pillet & Marin Todorov
7. Yet Another Swift Bloghttps://www.vadimbulavin.com
64
Thanks for attention
Taras Chernysh
[iOS Team]

More Related Content

What's hot

What's hot (20)

Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
Reactive Card Magic: Understanding Spring WebFlux and Project ReactorReactive Card Magic: Understanding Spring WebFlux and Project Reactor
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
 
Tracing 2000+ polyglot microservices at Uber with Jaeger and OpenTracing
Tracing 2000+ polyglot microservices at Uber with Jaeger and OpenTracingTracing 2000+ polyglot microservices at Uber with Jaeger and OpenTracing
Tracing 2000+ polyglot microservices at Uber with Jaeger and OpenTracing
 
Project Reactor Now and Tomorrow
Project Reactor Now and TomorrowProject Reactor Now and Tomorrow
Project Reactor Now and Tomorrow
 
Sonarlint
SonarlintSonarlint
Sonarlint
 
Contract Testing
Contract TestingContract Testing
Contract Testing
 
OpenTelemetry For Developers
OpenTelemetry For DevelopersOpenTelemetry For Developers
OpenTelemetry For Developers
 
Swift in SwiftUI
Swift in SwiftUISwift in SwiftUI
Swift in SwiftUI
 
Distributed tracing 101
Distributed tracing 101Distributed tracing 101
Distributed tracing 101
 
Embracing Observability in CI/CD with OpenTelemetry
Embracing Observability in CI/CD with OpenTelemetryEmbracing Observability in CI/CD with OpenTelemetry
Embracing Observability in CI/CD with OpenTelemetry
 
The Architecture of an API Platform
The Architecture of an API PlatformThe Architecture of an API Platform
The Architecture of an API Platform
 
Distributed tracing - get a grasp on your production
Distributed tracing - get a grasp on your productionDistributed tracing - get a grasp on your production
Distributed tracing - get a grasp on your production
 
GraphQL Data Loaders - How to feed your GraphQL API with data the smart way
GraphQL Data Loaders - How to feed your GraphQL API with data the smart wayGraphQL Data Loaders - How to feed your GraphQL API with data the smart way
GraphQL Data Loaders - How to feed your GraphQL API with data the smart way
 
Understanding Reactive Programming
Understanding Reactive ProgrammingUnderstanding Reactive Programming
Understanding Reactive Programming
 
Swift UI - Declarative Programming [Pramati Technologies]
Swift UI - Declarative Programming [Pramati Technologies]Swift UI - Declarative Programming [Pramati Technologies]
Swift UI - Declarative Programming [Pramati Technologies]
 
Api complete life cycle with api security
Api complete life cycle with api securityApi complete life cycle with api security
Api complete life cycle with api security
 
RxSwift to Combine
RxSwift to CombineRxSwift to Combine
RxSwift to Combine
 
Testing Your APIs: Postman, Newman, and Beyond
Testing Your APIs: Postman, Newman, and BeyondTesting Your APIs: Postman, Newman, and Beyond
Testing Your APIs: Postman, Newman, and Beyond
 
Swagger With REST APIs.pptx.pdf
Swagger With REST APIs.pptx.pdfSwagger With REST APIs.pptx.pdf
Swagger With REST APIs.pptx.pdf
 
Introducing Swagger
Introducing SwaggerIntroducing Swagger
Introducing Swagger
 
API Developer Experience: Why it Matters, and How Documenting Your API with S...
API Developer Experience: Why it Matters, and How Documenting Your API with S...API Developer Experience: Why it Matters, and How Documenting Your API with S...
API Developer Experience: Why it Matters, and How Documenting Your API with S...
 

Similar to Combine Framework

Similar to Combine Framework (20)

Guide to Spring Reactive Programming using WebFlux
Guide to Spring Reactive Programming using WebFluxGuide to Spring Reactive Programming using WebFlux
Guide to Spring Reactive Programming using WebFlux
 
Reactors.io
Reactors.ioReactors.io
Reactors.io
 
Reactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring BootReactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring Boot
 
operating system
operating systemoperating system
operating system
 
Angular 16 – the rise of Signals
Angular 16 – the rise of SignalsAngular 16 – the rise of Signals
Angular 16 – the rise of Signals
 
RxJava pour Android : présentation lors du GDG Android Montréal
RxJava pour Android : présentation lors du GDG Android MontréalRxJava pour Android : présentation lors du GDG Android Montréal
RxJava pour Android : présentation lors du GDG Android Montréal
 
Reactive Programming in Java and Spring Framework 5
Reactive Programming in Java and Spring Framework 5Reactive Programming in Java and Spring Framework 5
Reactive Programming in Java and Spring Framework 5
 
Loadrunner interview questions and answers
Loadrunner interview questions and answersLoadrunner interview questions and answers
Loadrunner interview questions and answers
 
JAN CARL BRIONES-Writing Programs Using Loops.pptx
JAN CARL BRIONES-Writing Programs Using Loops.pptxJAN CARL BRIONES-Writing Programs Using Loops.pptx
JAN CARL BRIONES-Writing Programs Using Loops.pptx
 
Microservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive ProgrammingMicroservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive Programming
 
Redux workshop
Redux workshopRedux workshop
Redux workshop
 
RxJava 2 Reactive extensions for the JVM
RxJava 2  Reactive extensions for the JVMRxJava 2  Reactive extensions for the JVM
RxJava 2 Reactive extensions for the JVM
 
How To Upgrade The React 18 Release Candidate.pptx
How To Upgrade The React 18 Release Candidate.pptxHow To Upgrade The React 18 Release Candidate.pptx
How To Upgrade The React 18 Release Candidate.pptx
 
Iot hub agent
Iot hub agentIot hub agent
Iot hub agent
 
How to build typing indicator in a Chat app
How to build typing indicator in a Chat appHow to build typing indicator in a Chat app
How to build typing indicator in a Chat app
 
Reactive programming with cycle.js
Reactive programming with cycle.jsReactive programming with cycle.js
Reactive programming with cycle.js
 
Vb6.0 intro
Vb6.0 introVb6.0 intro
Vb6.0 intro
 
Reactive programming with rx java
Reactive programming with rx javaReactive programming with rx java
Reactive programming with rx java
 
Building responsive applications with Rx - CodeMash2017 - Tamir Dresher
Building responsive applications with Rx  - CodeMash2017 - Tamir DresherBuilding responsive applications with Rx  - CodeMash2017 - Tamir Dresher
Building responsive applications with Rx - CodeMash2017 - Tamir Dresher
 
Java script
Java scriptJava script
Java script
 

More from Cleveroad

More from Cleveroad (18)

Tokenized projects. Should I work with them or give them up right away?
Tokenized projects. Should I work with them or give them up right away?Tokenized projects. Should I work with them or give them up right away?
Tokenized projects. Should I work with them or give them up right away?
 
Pulse of FinTech. 5 tips and tricks for BA on Finance project
Pulse of FinTech. 5 tips and tricks for BA on Finance projectPulse of FinTech. 5 tips and tricks for BA on Finance project
Pulse of FinTech. 5 tips and tricks for BA on Finance project
 
System logistics based on cross-docking
System logistics based on cross-dockingSystem logistics based on cross-docking
System logistics based on cross-docking
 
Theme and style in Flutter
Theme and style in FlutterTheme and style in Flutter
Theme and style in Flutter
 
MWWM
MWWMMWWM
MWWM
 
Payments in Mobile Apps
Payments in Mobile AppsPayments in Mobile Apps
Payments in Mobile Apps
 
Communication plan
Communication planCommunication plan
Communication plan
 
What’s new in Swift 5.2-5.3
What’s new in Swift 5.2-5.3What’s new in Swift 5.2-5.3
What’s new in Swift 5.2-5.3
 
Streaming tools comparison
Streaming tools comparisonStreaming tools comparison
Streaming tools comparison
 
Frontend Designer Interactions.
Frontend Designer Interactions.Frontend Designer Interactions.
Frontend Designer Interactions.
 
ARcore vs ML-Kit
ARcore vs ML-KitARcore vs ML-Kit
ARcore vs ML-Kit
 
Risk management
Risk managementRisk management
Risk management
 
Flutter Design Features
Flutter Design FeaturesFlutter Design Features
Flutter Design Features
 
UX Methods and Practices
UX Methods and PracticesUX Methods and Practices
UX Methods and Practices
 
Ui perfomance
Ui perfomanceUi perfomance
Ui perfomance
 
Rest vs GraphQL
Rest vs GraphQLRest vs GraphQL
Rest vs GraphQL
 
SWOT-Analysis, 360 Degree Evaluation, Giving Feedbacks
SWOT-Analysis, 360 Degree Evaluation, Giving FeedbacksSWOT-Analysis, 360 Degree Evaluation, Giving Feedbacks
SWOT-Analysis, 360 Degree Evaluation, Giving Feedbacks
 
Socket.io v.0.8.3
Socket.io v.0.8.3Socket.io v.0.8.3
Socket.io v.0.8.3
 

Recently uploaded

Recently uploaded (20)

Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning Framework
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
GraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisGraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysis
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
 

Combine Framework

  • 2. 2 Combine A unified declarative API for processing values over time SwiftUI: 1. @State 2. @Binding 3. @ObservedObject Foundation: 1. Timer 2. NotificationCenter 3. URLSession 4. KVO Core Data: 1. FetchedRequest 2. NSManagedObject
  • 3. 3 ReactiveSwift vs Combine Rx ReactiveSwift Combine Deployment target iOS 8+ iOS 8+ iOS 13+ Platform supported macOS, iOS, watchOS, tvOS, and Linux macOS, iOS, watchOS, tvOS, and Linux. macOS, iOS, watchOS, tvOS, and UIKit for Mac. Framework consumption Third-party Third-party First-party Maintained by Open source Open source Apple UI bind RxCocoa ReactiveCocoa SwiftUI passwordTextField.rx.text.orEmpt y .bind(to: viewModel.password) .disposed(by: disposeBag) testLabel.reactive.text <~ signal.take(duringLifetimeOf: self) publisher.assign(to: .text, on: label) Error Management - + + Backpressure - - +
  • 4. 4 ReactiveSwift vs Combine Combine ReactiveSwift Publisher* Signal, SignalProducer Subscriber* Observer Value event: value(Output) Completion: finished failure(Error) Value event: value(Output) Completion: completed failed(Error) interrupted
  • 5. 5 Publishers Emit values over time to one or more interested parties, such as subscribers. Including operation: math calculations, networking or handling user events, every publisher can emit multiple events types: 1. An output value of the publisher's generic Output type. 2. A successful completion. 3. A completion with an error of the publisher's Failure type. A publisher can emitzero or morevalues but onlyone completion event, which can either be a normal completion event or an error. Once a publisher emits a completion event, it’s finished and can no longer emit any more events. A publisher only emits an event when there’s at least one subscriber. Summary: 1. describe how values and errors are produced. 2. value type 3. allow registration of a Subscriber 4. don’t emit values or perform work if they don’t have any subscribers (exeption Future)
  • 7. 7 Publishers Combine provides a number of additional convenience publishers: ● Just ● Empty ● De!ered ● Future ● Sequence ● ObservebleObjectPublisher ● @Publisher ● Fail Just- a publisher that emits a single value to a subscriber and then complete. Future- asynchronouslyproduce a single result and then complete. Executes immediately when it is created instead of waiting for a subsc like a normal publisher does. They’re working with a Future that begins its execution immediately, emits a single value and re-emits the value to its subscribers if it receives more than a single subscriber. Reference type. De!eredallows to change from Future<Int, Never> to Deferred<Future<Int, Never>>. And than we have: ● The publisher will not perform work until it has subscribers ● If you subscribe to the same instance of this publisher more than once, the work will be repeated Emptypublisher type can be used to create a publisher that immediately emits a .finished completion event.
  • 8. Combine vs ReactiveSwift Publisher AnyPublisher 1. + 2. + 3. + 4. + Future 1+, 2-, 3+, 4+, 5- PassthroughSubject. / CurrentValueSubject 1-, 2+, 3-, 4+, 5+ SignalProducer 1. Signal producers start work on demand by creating signals 2. Each produced signal may send di!erent events at di!erent times 3. Disposing of a produced signal will interrupt it 4. Need to have a least one observer Signal 1. Signals start work when instantiated 2. Observing a signal does not have side e!ects 3. All observers of a signal see the same events in the same order 4. Terminating events dispose of signal resources 5. Has manually controlled signal (let (signal, observer) = Signal<Int, Never>.pipe()) 8
  • 9. Combine vs ReactiveSwift CurrentValueSubject MutableProperty 9 Observable boxes that always holds a value. This is a variables that can be observed for their changes.
  • 10. Subscribers 10 Responsible for requesting data and accepting the data (and possible failures) provided by a publisher. Initiates the request for data, and controls the amount of data it receives. Described with two associated types, one for Input and one for Failure. Summary: ● receives values and a completion ● reference type
  • 12. Subscription 12 Subscription represents a connection between a publisher and subscriber. Subscription allows: ● cancel subscription ● backpressure
  • 16. Subjects 16 Special case of publisher that also adhere to the subject protocol. This protocol requires subjects to have a.send() method to allow the developer to send specific values to a subscriber (or pipeline). Subjects can be used to "inject" values into a stream, by calling the subject’s .send() method. A subject will not signal for demand to its connected publishers until it has received at least one subscriber. itself. When it receives any demand, it then signals for unlimited demand to connected publishers. There are two types: 1. CurrentValueSubject 2. PassthroughSubject.
  • 18. Backpressure 18 Backpressure resolves around strategies to deal with Publishers that emit too many values, too rapidly Situation: publisher emits 10000 values per second.
  • 19. Life cycle 19 ● When the subscriber is attached to a publisher, it starts with a call to.subscribe(Subscriber). ● The publisher in turn acknowledges the subscription callingreceive(subscription). ● After the subscription has been acknowledged, the subscriber requestsNvalues withrequest(_ : Demand). ● The publisher may then (as it has values) sendingN(or fewer)values: receive(_ : Input). A publisher should never sendmore than the demand requested. Also after the subscription has been acknowledged, the subscriber can send cancellation with.cancel().A publisher may optionally sendcompletion: receive(completion:).A completion can be either a normal termination, or may be a .failure completion, optionally propogat an error type. A pipeline that has been cancelled will n send any completions.
  • 20. Operators 20 Combine provides two built-in subscribers, which make working with data streams straightforward: 1. Thesinksubscriber allows you to provide closures with your code that will receive output values and com From there, you can do anything your heart desires with the received events. 2. Theassignsubscriber allows you to, without the need of custom code,bindthe resulting output to some property on your data model or on a UI control to display the data directly on-screen via a key path.
  • 21. Operators 21 An object that acts both like a subscriber and a publisher. Operators are classes that adopt both the Subscriber protocol and Publisher protocol. They support subscribing to a publisher, and sending results to any subscribers. You can create chains of these together, for processing, reacting, and transforming the data provided by a publish requested by the subscriber.
  • 22. 22 OperatorsMap ● map<T>(_:) ● map<T0, T1>(_:_:) ● map<T0, T1, T2>(_:_:_:)
  • 23. 23 OperatorstryMap The map operator allows for any combination of Output and Failure type and passes them through. tryMap accepts any Input, Failure types, and allows any Output type, but will always output an <Error> failure type.
  • 24. 24 Operators flatMap It uses when you want to reach into inner publisher to get its elements
  • 30. 30 Operators Drop Imagine a scenario where you have a user tapping a button, but you want to ignore all taps until your isReady p some result. This operator is perfect for this sort of condition.
  • 31. 31 Operators Prefix The prefix family of operators is similar to the drop family and provides prefix(_:), prefix(while:) and prefix(untilOu However, instead of dropping values until some condition is met, the prefix operatorstakevalues until that condition is met.
  • 40. 40 Error handle Common operators you might want to try out: ● assertNoFailure (which will change the error type to Never and calls an assert when an error occurs) ● mapError ● retry ● catch ● replaceError
  • 41. 41 Debugging Fortunately, there are ways to debug in Combine with use of the following operators: ● Print ( to print log messages for all publishing events) ● Breakpoint ( which raises the debugger signal when a provided closure needs to stop the process in the debugger) ● breakpointOnError (which only raises the debugger upon receiving a failure) ● Timelane tool (https://github.com/icanzilb/Timelane/rel eases/tag/1.3) and add dependency to project https://github.com/icanzilb/TimelaneCo mb
  • 47. 47 Combine in practice Manually controlled publisher (like Signal<Input, Error>.pipe()) and observe current value (like MutableProperty)
  • 49. 49 Combine in practice TASK:Imagine that you want to make a single network call that multiple objects subscribe to without making a new network call. share()operator returns an instance of the Publishers.Share class. This new publisher “shares” the upstream publisher. It will subscribe to the upstream publisher once, with the first incoming subscriber.
  • 50. 50 Combine in practice TASK:Imagine that you want to make a single network call that multiple objects subscribe to without making a new network call.
  • 51. 51 Combine in practice TASK:Imagine that you want to make a single network call that multiple objects subscribe to without making a new network call.
  • 52. 52 Combine in practice TASK:Multiple requests using array ids
  • 53. 53 Combine in practice TASK:Imagine that you want to make a single network call that multiple objects subscribe to without making a new network call. The reason for this is that the Future executed immediately, and repeats its output. Reference type. Wrapping a Future in Deferred makes it behave exactly the same as any other Publisher
  • 55. 55 Combine in practice Schedulars By default, several objects that you might be familiar with already conform to the Scheduler protocol: 1) RunLoop 2) DispatchQueue 3) OperationQueue When you applyreceive(on:)to a publisher it will make sure that all events are delivered downstream on the scheduler you provide. Possition make sence. Subscribe(on:)- specifies the scheduler on which to perform subscribe, cancel, and request operations.
  • 59. Background task (exeption URLSession) 59 A lot of publishers will emit values on the queue they received their subscriber on, but this is not always the case. DataTaskPublisher is set up to publish its values o! the main thread at all ti
  • 60. Multicast 60 A publisher conforming to ConnectablePublisher will have an additional mechanism to start the flow of data after a subscriber has provided a request. This could be .autoconnect(), which will start the flow of data as soon as a subscriber requests it. The other option is a separate .connect() call on the publisher itself.
  • 63. 63 List of references : 1. Combine framework https://medium.com/flawless-app-stories/combine-framework-in-swift-b730ccde131 2. SwiftLeehttps://www.avanderlee.com/swift/combine/ 3. Rx vs Combine https://medium.com/gett-engineering/rxswift-to-apples-combine-cheat-sheet-e9ce 32b14c5b 4. Di!https://dzone.com/articles/combine-vs-rxswift-introduction-to-combine-amp-dif 5. Using Combine - Joseph Heck 6. Combine Asynchronous Programming with Swift_v1.0.2 By Scott Gardner, Shai Mishali, Florent Pillet & Marin Todorov 7. Yet Another Swift Bloghttps://www.vadimbulavin.com
  • 64. 64 Thanks for attention Taras Chernysh [iOS Team]