访问传递给回调函数的参数

时间:2019-06-25 16:25:48

标签: android kotlin

我有一个实现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 )
    }
}

我将两个参数传递给此类,即:

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()

一切正常,除了我似乎无法找到一种方法来访问回调函数中的参数:

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";
}

有什么建议吗?谢谢!

1 个答案:

答案 0 :(得分:1)

Collection