Kristian
Kristian

Reputation: 133

Accessing the argument which was passed to the callback function

I have a simple class which implements the AsyncTask:

class Async( private val workload: () -> String,
             private val callback: ( httpResponse : String ) -> Unit
) : AsyncTask<String, String, String>()
{
    override fun doInBackground( vararg params: String? ): String?
    {
        return workload()
    }

    override fun onPostExecute( result: String )
    {
        callback( result ) // <-- argument being passed to the callback
        super.onPostExecute( result )
    }
}

I pass two arguments to this class, which are:

string workload() - function which takes long time to execute and returns a string
callback( string ) - the callback function to which I want to pass the value, which was returned by the workload()

Everything works fine, except that I can't seem to be able to find a way how to access the argument within the callback function:

Async(
    {
        workload()
    },
    {
        // how to "receive" the "test" string returned by the workload()? 
        Log.d( "myapp", ???_argumentPassedToCallback_??? );
    }
).execute( "" )


fun workload() : String
{
    Thread.sleep( 1000 )     
    return "test";
}

Any suggestions please? Thank you!

Upvotes: 0

Views: 29

Answers (1)

Francesc
Francesc

Reputation: 29260

Async(
    {
        workload()
    },
    { response ->
      Log.d("foo", "The response is: $response")
    }
).execute( "" )

Upvotes: 1

Related Questions