Search code examples
rubyjsonrubymotion

How do I synchronously call HTTP api in Ruby Motion


In my controller I would like to wait/block until the http request has returned data before attempting to load the table. Currently, it throws error when fetching @data.count after setting datasource:

 def viewDidLoad
  super
  self.title = "my categories"
  @table = UITableView.alloc.initWithFrame(self.view.bounds)


  @data = nil

  //how to call this next line synchronously ?
  create_data


  @table.dataSource = self
  self.view.addSubview @table
 end

 def create_data
     BW::HTTP.get("http://website.com/api/v1/category") do |response|
     if response.ok?
    p "response was ok"
    mydata = BW::JSON.parse(response.body.to_str)
    mydata.each {           
        |item|
         @data << Item.new(item)
         p "test"
    }
    else
       warn "problem"
    end
  end
end

How can I do it?


Solution

  • You shouldn't wait.

    You should probably just initialise @data to an empty array to start. This will avoid the exception and prevent the need to block the UI thread, which you should avoid at all costs.

    So replace

    @data = nil
    

    with

    @data = []