-1

I had a very slow bottom sheet, showing up blank then after a while loading data. I tried to apply a completionHandler isLoadedCompletionHandler, solution worked, but my colleague told me this is not a "completion handler". Could you explain me why this is working. And how? Is this a proper completion handler?

func buttonDetailTapped(with travelSolutionId: String) {
           guard let currentPurchaseSolution = purchaseSolutions.value.first(where: { $0.xmlId == purchaselSolutionId }) else {return}

           getAllPurchaseDetail(searchId: searchId.value, solutionId: purchaseSolutionId)
               .subscribe(onNext: { [weak self] purchaseDetails in
                   let isLoadedCompletionHandler: ([PurchaseDetail]) -> Void = { theArray in
                       self?.result.onNext(.showPurhcaseSolutionDetails(purchaseDetails, currentTravelSolution))
                   }
                   isLoadedCompletionHandler(purchaseDetails)
               })
               .disposed(by: disposeBag)
       }
JeremyP
  • 84,577
  • 15
  • 123
  • 161
biggreentree
  • 1,633
  • 3
  • 20
  • 35
  • 1
    The currently shown code is the code after you "tried to apply a completionHandler", right? Can you show the code before you "tried to apply a completionHandler"? – Sweeper Oct 17 '19 at 09:30

2 Answers2

0

A completion handler is a function that you pass into your function, which usually gets called upon the completion of some asynchronous task.

Your function of buttonDetailTapped contains no parameters that are functions (i.e. (Thing, Error) -> Void) which are called upon completion, and thus you cannot know from calling this function when it completes.

Your function may go ahead and do other things when it's done, but there is no completion handler.

MQLN
  • 2,292
  • 2
  • 18
  • 33
  • How would you implemented it – biggreentree Oct 17 '19 at 09:16
  • There are a lot of great resources for learning Swift from scratch online! SO is a wonderful place to get insight into a lot of questions, but what you're asking is too broad. Check out this link for more info, including complete implementation details: https://grokswift.com/completion-handler-faqs/ – MQLN Oct 17 '19 at 12:21
0

isLoadedCompletionHandler is not a completion handler because it is called immediately after it is assigned.

A completion handler is a closure that you pass into a function, that will be called when whatever that function is doing asynchronously completes. You are not passing isLoadedCompletionHandler anywhere.

You could have just written

getAllPurchaseDetail(searchId: searchId.value, solutionId: purchaseSolutionId)
    .subscribe(onNext: { [weak self] purchaseDetails in
        self?.result.onNext(.showPurhcaseSolutionDetails(purchaseDetails, currentTravelSolution))
   })
   .disposed(by: disposeBag)

and achieved the same result.

Sweeper
  • 213,210
  • 22
  • 193
  • 313