Search code examples
rubymultithreadingrubymotion

How to wait for a call to initialize a variable in Rubymotion?


Can we make some process wait for a variable to be initialized and then continue?

I have the following code:

  def viewDidLoad
    BW::Location.get(distance_filter: 10, desired_accuracy: :best) do |result|
      if result[:error].nil?
        lat = result[:to].latitude
        lng = result[:to].longitude
      end
      BW::HTTP.get("APIURL" |response|
        case response.status_code
          when 200
          parsed_json = BW::JSON.parse(response.body)
          if parsed_json[:tags]
            App::Persistence['tag'] = parsed_json[:tags]
          else
            UIApplication.sharedApplication.delegate.logged_out
          end
        end
      end
    end    

    def imagePickerController(picker, didFinishPickingMediaWithInfo: info)
      begin
        App.alert('hello')
      end while App::Persistence['tag'].nil?
    end
    App.alert("Finish")
  end

When the photo is taken, there is a possibility that my App::Persistence['tag'] hasn't received the value from the API call yet. Therefore, when the user clicks the 'Next' button, I want to make them wait for App::Persistence['tag'] to get initialized before proceeding.

This does not seem to work and it goes on to alert "finish".


Solution

  • An easy solution is to put the post-picking/camera business logic into it's own method, then when the image picker/camera finishes, if the tag is ready, call that business logic method then, if it's not ready, setup KVO to listen out for the tag to change maybe, and store the info from the picker/camera, then once KVO picks up that the tag is ready, it will call your business logic method (or a method that calls your business logic method).

    attr_accessor :cameraInfo
    
    def doTheThing
      # your business logic, do something with self.cameraInfo
      self.cameraInfo = nil
    end
    
    def imagePickerController(picker, didFinishPickingMediaWithInfo: info)
      self.cameraInfo = info
      if App::Persistence['tag'].nil?
        # setup KVO or some basic loop in another thread or something along those lines
      else
        doTheThing
      end
    end