0

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"

  • 2
    _its not clear to me what the "result of the call" is_ Why is it not clear? `fetchCurrentAuthSession` is a function that returns, as its result, an AnyCancellable. You are calling the function but throwing that result away. The compiler thinks your code might be unintentionally useless, and it is right about that. – matt Apr 17 '22 at 14:40
  • @matt *what the "result of the call" is* | I understand the result of the call is returning a type of `AnyCancelable` but I am too new to swift to understand what object it is actually supposed to be retuning. *or how I should be "using it"* | After I call the function, what syntax is required to allow me to consume it's returned value. –  Apr 17 '22 at 14:51
  • 1
    You have not explained what you think you are doing or wish to do. It's like you have some Combine code and you threw it into your Button code with no idea what Combine is or how to use it. – matt Apr 17 '22 at 14:53
  • @dp38922 The `AnyCancallable` you get is like a "token" that's tied to the lifetime to the combine subscription. Once all outstanding strong references to it expire, it will be deinitialized, and in the process, it will cancel the combine subscription (so it doesn't go on forever). The correct way to "use it" is to store it, in a place whose lifetime is equivalent to the lifetime you want the subscription you want to have. E.g. if you're making an API call to auth the user, you want that combine subscription to live at least as long as that call takes – Alexander Apr 17 '22 at 15:15

1 Answers1

3

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.

vadian
  • 274,689
  • 30
  • 353
  • 361