Jump to content

[TOPIC: topicViewTemplate]
[GLOBAL: userSmallPhoto]

Network Request without Listeners?
Started by rts Apr 27 2018 01:14 PM

1 reply to this topic
network requests http
This topic has been archived. This means that you cannot reply to this topic.
[TOPIC: post.html]


[GLOBAL: userInfoPane.html]
  • Observer

  • 1 posts
  • Corona SDK



I'm relatively new to Corona and Lua and have been trying to implement some API calls within my game. However, I've been creating multiple network requests and unique listeners for each one but is there an easier way?


I estimate there to be about 15 different API calls in my game as the server delivers a fair bit of content. However, having all of these listeners seems a bit tedious and any ways to make this more efficient would be appreciated.



[TOPIC: post.html]


[GLOBAL: userInfoPane.html]
  • Corona Geek

  • 7,666 posts
  • Corona SDK

I'm not sure what you're doing exactly, but when I find myself in a situation where I need to make many network requests that do similar things and use a similar listener I do one of two things:


1. Write a single homogeneous listener that can be used for all requests


2. Write a generator/wrapper that  both generates a custom listener and issues the request.




This is an example of the latter:

local baseURL = "https://raw.githubusercontent.com/roaminggamer/RG_FreeStuff/master/AskEd/common/cards/"

local function createCard( x, y, w, h, num )
   local tmp = display.newRect( x, y, w, h )

   local function networkListener( event )
      if ( event.isError ) then
         display.remove( tmp )
       elseif ( event.phase == "ended" ) then
         tmp.isVisible = true
         tmp.fill = { type = "image", filename = event.response.filename, baseDir = event.response.baseDirectory }

   local to    = "cardClubs" .. num .. ".png"
   local from  = baseURL .. to   

   local params = {}
   network.download( from, "GET", networkListener, params, to, system.TemporaryDirectory )

It is kind a silly example, but it shows how, knowing a little of what is common in the use cases, I can make a wrapper to generate most of the code I would otherwise write by hand over and over.