user18365424
user18365424

Reputation:

Result of call is unused with Combine

I have this function

import Foundation
import Combine
import Amplify

func fetchCurrentAuthSession() -> AnyCancellable {
    Amplify.Auth.fetchAuthSession().resultPublisher
        .sink {
            if case let .failure(authError) = $0 {
                print("Fetch session failed with error \(authError)")
            }
        }
receiveValue: { session in
    print("Is user signed in - \(session.isSignedIn)")
}
}

and I am calling it like this

 Button(action: {
          print("button pressed")
          fetchCurrentAuthSession()
          
        }) {
          Text("Authenticated Test")
        }

I get the Xcode warning Result of call to 'fetchCurrentAuthSession()' is unused

its not clear to me what the "result of the call" is, or how I should be "using it"

Upvotes: 0

Views: 3724

Answers (1)

vadian
vadian

Reputation: 285069

Be aware that sink is just another operator and that neither the receivedValue nor the completion is the result of the pipeline.

You have to store the actual result, the AnyCancellable object, into a property.

It's similar to other asynchronous patterns. You need a strong reference to the object to keep it alive until the job is done.

var cancellable : AnyCancellable?

func fetchCurrentAuthSession() {
    cancellable = Amplify.Auth.fetchAuthSession().resultPublisher
        .sink....

As the name implies a huge benefit is that you are able to cancel the pipeline.

Upvotes: 5

Related Questions