2

Specifically trying do some non-blocking http operations within a UI context.

  1. I read up on coroutines whicch blew my tiny mind, couldn't work out how to invoke a declarative suspend method from a UI event.

  2. Had a fair crack with AsyncTask in conjunction with URL(addr).openStream(), which seemed ok, but I couldn't seem find any good examples where a lambda was being passed in for the oncomplete processing. All the examples seemed to just directly name the control instances in the in the onPostExecute function.

I was keen to find a more reusable pattern, perhaps in the styley of jquery's ajax pattern.

  1. The Fuel http client library seems pretty good, I've knocked this together which seems to do the trick:

    val url_public_ip: String = "http://ipinfo.io/json"
    val url_fake_data: String = "https://jsonplaceholder.typicode.com/photos"
    
    fun btnGetPublicIp_Click(view: View){
        getData(url_public_ip, txtData) 
    }
    
    fun btnGetMockData_Click(view: View){
        getData(url_fake_data, txtData) 
    }
    
    fun getData(url: String, control: TextView){
        control.text = "Querying..."
    
        // Fuel based async request.
        url.httpGet().responseString { request, response, result ->
            when (result) {
                is Result.Failure -> {
                    var error: String? = result.getAs()
    
                    control.text = error
                }
                is Result.Success -> {
                    var data: String? = result.getAs()
    
                    control.text = data
                }
            }
        } 
    }
    

So, the question:

Is anyone else using other custom libs to do this & what kinda stuff are you guys using?

dbl4k
  • 71
  • 6

0 Answers0