Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change thread using combine Publisher?

I am using Combine and SwiftUI to do some async stuff, the point is that I don't know how to receive the response from the asynchronous operation in the main thread. The apple doc says that it can be used the RunLoop.main, but currently in Swift 5.0 it isn't a Scheduler. So any ideas about this?

I have tried to use as per apple doc, but no luck.

anyPublisher
    .receiveOn(on: RunLoop.main)
like image 886
Alberto Penas Avatar asked Jun 11 '19 20:06

Alberto Penas


People also ask

What does combine sink do?

What's a sink? While a complete explanation of Combine, publishers, subscribers, and sinks is beyond the scope of this article, for our purposes here it's probably enough to know that in Combine a sink is the code receives data and completion events or errors from a publisher and deals with them.

What is future in combine?

import Combine 'Future' means 'A publisher that eventually produces a single value and then finishes or fails' and It provide closure as Future. Promise it has Result type parameter without return value. Declaration.

What is combine scheduler?

The Combine framework provides the Scheduler protocol, which is a powerful abstraction for describing how and when units of work are executed. It unifies many disparate ways of executing work, such as DispatchQueue , RunLoop and OperationQueue .

What is publisher in combine?

Publisher defines how values and errors are produced. Publishers allow registration of a subscriber. A publisher provides data when available and upon request. A publisher that has not had any subscription requests will not provide any data.


1 Answers

Combine - at the time of writing - is not fully integrated in Foundation.

According to Xcode 11 Beta Release Notes:

The Foundation integration for the Combine framework is unavailable. The following Foundation and Grand Central Dispatch integrations with Combine are unavailable: KeyValueObserving, NotificationCenter, RunLoop, OperationQueue, Timer, URLSession, DispatchQueue, JSONEncoder, JSONDecoder, PropertyListEncoder, PropertyListDecoder, and the @Published property wrapper. (51241500)


As per the latest Xcode 11 beta (2), this has been fixed, so expect your code to work correctly.

The Foundation integration for the Combine framework is now available. The following Foundation and Grand Central Dispatch integrations with Combine are available: KeyValueObserving, NotificationCenter, RunLoop, OperationQueue, Timer, URLSession, DispatchQueue, JSONEncoder, JSONDecoder, PropertyListEncoder, PropertyListDecoder, and the @Published property wrapper. (51241500)

Thanks to @Martin R and @silicon_valley for the update.

like image 73
Matteo Pacini Avatar answered Nov 15 '22 08:11

Matteo Pacini