What is the iOS (or RubyMotion) idiom for waiting on a block that executes asynchronously?

后端 未结 4 1153
醉梦人生
醉梦人生 2021-01-03 12:59

I have been pulling my hair out for weeks on this niggling problem, and I just can\'t find any info or tips on how or what to do, so I\'m hoping someone here on the RubyMoti

相关标签:
4条回答
  • 2021-01-03 13:01

    When you need to display the payment options, display a HUD, like MBProgressHUD to block the user from using the UI and then start your network call. When the network call returns, dismiss the HUD in either in your success/failure blocks or in the delegate methods and then refresh your view with the data received.

    If you don't like the HUD idea you can display something appropriate in your UI, like a UILabel with "loading..." or an UIActivityIndicatorView.

    If you need to get the data to display first thing, do it in viewDidAppear; if it happens on an action then move your transition to the next view (performSegueWithIdentifier or whatever) into your network success block/callback and make the network call when the action is called.

    There should be examples in your networking library of how, or take a look at the usage sample code in MBProgressHUD itself https://github.com/jdg/MBProgressHUD.

    0 讨论(0)
  • 2021-01-03 13:13

    as borrrden just said, I'd use a dispatch_semaphore

     def ApiHelper.make_sync(&block)
       @semaphore = Dispatch::Semaphore.new(0)
       BubbleWrap::Reactor.schedule do
         # do your stuff
         @result = block.call()
         @semaphore.signal
       end
       @semaphore.wait
       @result
     end
    

    this is how I'd handle it on Rubymotion

    0 讨论(0)
  • 2021-01-03 13:13

    You can also use synced queues.

    Dispatch::Queue.new('name').sync
    
    Dispatch::Queue.main.sync
    

    Take a look at more examples of usage: http://blog.arkency.com/2014/08/concurrent-patterns-in-rubymotion/

    0 讨论(0)
  • 2021-01-03 13:26

    Here's what I do to make multi-threaded synchronized asynchronous calls.

    def make_sync2(&block)
      @semaphore ||= Dispatch::Semaphore.new(0)
      @semaphore2 ||= Dispatch::Semaphore.new(1)
      BubbleWrap::Reactor.schedule do
        result = block.call("Mateus")
        @semaphore2.wait # Wait for access to @result
        @result = result
        @semaphore.signal
      end
      @semaphore.wait # Wait for async task to complete
      result = @result
      @semaphore2.signal
      result
    end
    
    0 讨论(0)
提交回复
热议问题