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

↘锁芯ラ 提交于 2019-11-30 16:43:09

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.

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

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

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/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!