2,098 questions
0
votes
0
answers
70
views
Using Combine for the first time. XCTTest completes before combine promise is fulfilled
func getCharactersList(from url: URL) -> AnyPublisher<[Character], NetworkRequestError> {
if shouldReturnError {
// Fail with concrete NetworkRequestError
return Fail(...
0
votes
1
answer
108
views
How to synchronize multiple marquee animations and resetting them when text changed?
I am trying to create a SwiftUI Marquee component that:
Can take 2 string items
If any of the two string items are longer then the width of its parent then animate them right to left
If they are ...
1
vote
1
answer
60
views
How can I get a Subscriber to subscribe to get only 4 elements from an array?
I am trying to implement a subscriber which specifies its own demand for how many elements it wants to receive from a publisher.
My code is below:
import Combine
var array = [1, 2, 3, 4, 5, 6, 7]
...
-1
votes
1
answer
170
views
Implementing Combine map operator that read data from MainActor
I have a feeling that Swift Concurrency is fighting agains me all the time. It is really frustrating.
My problem. I need to create Combine publisher to emit battery state on iOS device.
So far I have ...
4
votes
2
answers
1k
views
How to solve Sending 'self.viewModel' risks causing data races? [closed]
I am looking to migrate my below file into swift 6.
There is one way to forcefully use @MainActor everywhere(ViewModels, protocols etc)
another is use uncheck-sendable or use @preconcurrency.
But I am ...
1
vote
1
answer
118
views
RxSwift's Signal equivalent in Combine / Concurrency
I have been using RxSwift for my apps before Combine, Swift Concurrency and SwiftUI. In RxSwift we can have a Signal that will just emit without replaying the previous value which is very useful to ...
0
votes
0
answers
37
views
Swift 6 only Combine crash [duplicate]
@globalActor
public struct TestGlobalActor {
public actor ActorType { }
public static let shared: ActorType = ActorType()
}
final class TestCrash: XCTestCase {
let subject = ...
1
vote
2
answers
217
views
How to make a Set<AnyCancellable> sendable?
How can I get rid of @unchecked Sendable in this case:
final class TestSendable: @unchecked Sendable {
private var subscriptions = Set<AnyCancellable>()
}
apart from:
@MainActor ...
-1
votes
2
answers
71
views
How to create custom Generic Subscriber with Combine?
Here is my CustomSubscriber. All I want to achieve is to replace build-in .sink with my own one. Just to better understand how it works under the hood.
class CustomSubscriber<Input, Failure>: ...
-2
votes
1
answer
89
views
Where would using Record Publisher with Combine be useful?
I am trying to understand Record Publisher.
Here is an example to better understand the case:
var subscriptions = [AnyCancellable]()
let pub = Record<Int, Never>(output: [1, 101, 102, 1001, 1002]...
0
votes
1
answer
59
views
How to repeatedly connect a timer with onTapGesture?
As title says I have created a timer to publish every second and on the 5th second it disables a picker in my view. The timer itself is started by tapping on the picker and it works on the first try ...
0
votes
1
answer
38
views
Adding Publisher conformance to a class breaks expected computed property getter calls
I’ve encountered unexpected behavior in Swift when a class conforms to Publisher. It appears that just conforming to the protocol causes property getters and setters to stop being called.
Reproducible ...
0
votes
0
answers
61
views
Expose a @Published var from an Actor protocol in Swift 6 [duplicate]
I want to listen to the changes (of a boolean for example) value in one of my actors.
So I have this protocol that my actor conforms to:
protocol MyServiceProtocol: Actor {
var myValuePublisher: ...
0
votes
1
answer
50
views
Can you use a combine publisher to stagger events so that they are output a minimum time apart from eachother?
For an animation, I am trying to use Combine to smooth out the animation.
There are three image URLs that need to be loaded. I am hoping to make it so that they are loaded in parallel, but that no ...
0
votes
0
answers
31
views
How to cancel all publishers when any send error?
code: 50 publishers, I want to that: any send error, all will stop. Just like RxSwift
let singles: [Deferred<Future<Int, Error>>] = (0..<50).compactMap { value in
return ...
-2
votes
1
answer
86
views
Create Publisher that emits when month changes
TL:DR Is it possible to create a Publisher that will emit whenever the date ticks over from one month to the next (i.e. at 00:00 on 1st of each month) regardless of whether the app is in the ...
1
vote
1
answer
59
views
Throttle gives two updates
I am struggling to understand the behavior of throttle. When I click the button multiple times, instead of seeing "sink" printed once and all the other being dropped by the throttle, it will ...
1
vote
1
answer
495
views
How to convert async function/method to publisher in Swift 6
I tried to make as simple example as possible using Swift 6 to produce this problem which I am having difficulty to solve:
func getValue() async -> Int { 0 }
func getValuePublisher() -> ...
2
votes
1
answer
164
views
Can you update ansible dictionary on the fly?
I have a dict/json type of object that I captured from the output of a REST API call, let's say it's in a variable/register named ouput. The data looks like below. For completeness, I shared the ...
0
votes
1
answer
56
views
Can't use eraseToAnyPublisher after a collect "Type of expression is ambiguous without a type annotation"
I have two deferred publishers emitting an array of Ints. They are Futures under the hood of that maters.
I would like to have these two publishers "run" in parallel so lets say p1 returns [...
0
votes
1
answer
177
views
SwiftUI, Combine: pass @Published property as a @Binding to another object (delegation style)
I have a following synthetic example:
final class MainViewModel: ObservableObject {
@Published var response: String?
func makeSecondaryViewModel() -> SecondaryViewModel {
...
0
votes
0
answers
392
views
withObservationTracking not detecting property changes in a @Observable model stored within a UIKit Cell and modified from a UIViewController
I am building an app that is mostly not a grid view. However there is one screen that is a grid view and because I need the extra preloading performance in order to prioritize fast scrolling image ...
4
votes
1
answer
667
views
Is CurrentValueSubject thread safe?
I was under the impression that Combine is supposed to be thread safe, even though the documentation is sparse. I noticed that when publishing to a CurrentValueSubject on a thread other than the one ...
2
votes
3
answers
143
views
How do I collect and send objectWillChange publisher?
I have a ObservableObject class that has a @Published variable that is mutable. I have a function that mutates the value on the ObservableObject class a number of times. How could I collect the ...
0
votes
0
answers
70
views
Proper way to update the UI in MVVM for components and systems in RealityKit
Following Apple's documentation on components, I think I understand the basic idea.
A component is an object that captures the state of an entity and can be manipulated by a system.
So far so good, I ...
-1
votes
1
answer
144
views
@StateObject preventing view updates and @ObservedObject initialises a new view model in every render [closed]
I want to use the MVVM approach to separate UI presentation logic from the view presentation itself. I'm doing it like this:
struct ViewA: View {
@StateObject var viewModel: ViewModel
...
-2
votes
1
answer
126
views
What does cancellable variable do in Swift Combine document?
So I having a trouble when reading the Convert incoming raw data to your types with Combine operators section of Processing URL session data task results with Combine article.
Here is the template ...
0
votes
0
answers
205
views
Can @Observable property changes be observed outside of views?
I have a simple Microphone class which conforms to @Observable, with public properties that trigger redraws for some SwiftUI Views. But I also want these property changes to trigger logic in non-Views,...
2
votes
1
answer
69
views
When using `last(where:)` operator, how get the emitted value?
Consider the following snippet:
enum MyError: Error {
case test
}
let subject = PassthroughSubject<Int, MyError>()
subject
.eraseToAnyPublisher()
.last(where: { $0 % 2 == 0 })
.sink(...
-1
votes
1
answer
98
views
Passing a mutable actor-isolated property to a async function [duplicate]
I'm trying to observe a publisher so that I wait till I encounter a particular value, at which point, I start a task. To have it play well with existing structured concurrency code, I added a ...
0
votes
1
answer
443
views
Swift 6 build errors when monitoring Published values of an Actor in a Task
The following code gives error when building under Swift 6 language version in Xcode. Is this an issue in architecture or has an easy fix? Type Bool is Sendable but it's publisher is not.
Non-sendable ...
0
votes
2
answers
136
views
Why can't I initialise AnyPublisher property in a class?
I want to initialise all properties in my class. I don't want isEmptyPublisher property to start working when it is first accessed. I want it to start working as soon as it is initialised.
Why can't I ...
1
vote
1
answer
328
views
How to Test Combine Code with .receive(on:) Without Injecting Schedulers?
I am using the Combine framework in my iOS project, and I am writing unit tests for my code. However, I encounter problems when testing code that uses schedulers. Here's an example of a function I ...
-1
votes
1
answer
184
views
How do I refresh my SwiftUI to changes in my view model?
I have a view model, that has a network service that returns us a Combine publisher. The VM reacts to this publisher by updating its state. And the UIViewController would then update based on the VM ...
8
votes
3
answers
3k
views
How to test Combine Publishers in Swift Testing?
Consider this XCTest-based unit test:
func testImageRetrieved() {
let expectation = XCTestExpectation()
let cancellable = viewModel.$image.dropFirst().sink { _ in
// Do nothing on completion.
...
1
vote
0
answers
389
views
How to unit test asynchronous Combine based code without XCTestExpectation or fixed waiting times [duplicate]
In iOS development using Swift, what options do I have for testing code that utilizes the Combine framework? Specifically, I'm looking to test a function that returns an AnyPublisher asynchronously. I ...
0
votes
1
answer
248
views
How to debounce text in swiftui and also assign when the view is closed?
I am writing a text editing field that autosaves to a server. I wrote this helper view to make debouncing such views simple.
The trick is I need to support when there is an initial value or when a new ...
1
vote
1
answer
478
views
How to initialize SwiftUI Map Camera on user's location?
I am trying to initialize my MapKit Map in SwiftUI using the User's Location I obtained from Core Location, currently I initialize my Map with a MapCameraPosition type Variable, how can I start the ...
0
votes
0
answers
282
views
Why can't I bind struct property of @Observable object inside of that object when I can do so outside of the object in SwiftUI?
When it comes to debouncing text fields I find just about every example does so in the view. And while this is ok I guess logically in my case it would be a better fit for the view model.
In theory ...
0
votes
1
answer
109
views
How Do I Mock TimerPublisher in Swift? -- 'autoconnect' cannot be used on 'any ConnectablePublisher<Date, Never>'
I'm trying to test my client code which uses Apple's Timer.publish(every:on:in:).
I want to control time in my unit tests to avoid using wait(for:timeout:) and be able to test everything synchronously....
2
votes
2
answers
426
views
How do I make a UserDefaults publisher behave consistently with multiple threads?
I am currently working on a system communicating some UserDefaults values to another system on change. I was trying to use UserDefaults.standard.publisher as seen in the example below to observe ...
0
votes
1
answer
135
views
Swift Combine: Preventing memory leaks with coordinator pattern and subscription management
I'm trying to use Combine instead of delegates while implementing the Coordinator pattern. However, when I remove a coordinator from the childCoordinators list, it causes a memory leak. How can I ...
0
votes
1
answer
123
views
Will multicast(_:) create a new subject for each subscriber
In this code, why debug: multicast triggered.. is printed only once while there are 2 subscribers. Since Apple says multicast(_:) creates a new publisher for each subscriber, shouldn't the print ...
0
votes
1
answer
222
views
os_unfair_lock_recursive_abort on Subscriber.receive(completion: .finished) in iOS 18
I have the following code for mapping ReactiveSwift SignalProducer to Combine Publisher:
import Combine
import Foundation
import ReactiveSwift
/// This is a custom Publisher that wraps SignalProducer
...
1
vote
1
answer
109
views
CPU Usage not updating
I’ve written SwiftUI code that uses Combine to display CPU usage metrics such as User, System, Nice, and Idle values for each core on the system. The functionality works initially in the sense that ...
-1
votes
1
answer
91
views
I have a problem in getting the data from api in English - iOS swift
here is the function , and in postman when I put Accept-Language "en" it get the data in English , but my code not , why
func fetchDataByToken<T: Decodable>(urlString: String, type: T....
0
votes
1
answer
68
views
I want to show the comment immediately on the screen with comments list
when I post comment I have to fetch the comment list (all product details) again to show the new comment
I use combine , any solution to show the comment immediately in the comments list when post?
...
2
votes
1
answer
424
views
Swift asynchronous sequence missing updates from @Published property
I’m encountering an issue in my app where a test occasionally fails. I’ve managed to narrow the problem down to this code snippet. The snippet contains two asynchronous sequences that both observe and ...
0
votes
1
answer
131
views
Swift Combine is leaking when using API subscribe<S>(_ subject: S) -> AnyCancellable
Example code:
class SwiftViewController: UIViewController {
private var cancellable: AnyCancellable?
override func viewDidLoad() {
super.viewDidLoad()
let ...
0
votes
1
answer
36
views
iOS Combine: using .delay in .flatMap results in data lost
I am learning Combine on iOS. This is my code:
struct ContentView: View {
let aiRepsonse = "View the latest news and breaking news today for U.S., world, weather, entertainment, politics and ...