Reputation: 115
In my application I need to perform Network calls using a specific framework. Because every network call need to be performed on the separate thread I would like to have one function which start new Thread perform a call and return an object. To do so I tried to use HigherOrderFunctions, but I didn't find until now how to declare function as an argument which take a variable number of arguments.
To give you an idea I would like to have something like this:
fun Client.performNetworkCall(calledFunction:(vararg Object)->Object):Object{
Thread(Runnable {
calledFunction
}).start()
//return function results
}
But it seems to impossible to declare such function. Is it possible in Kotlin? I would like avoid creating every time new thread in my code when I need to perform a network call. So that I can write something like this
client.performNetworkCall{ bean.createNewUser(User("","","Gosia","gosiak@gmail.com","pass"))}
bean is object of my interface which hava a function createNewUser. Function createNewUser is implement on server and will return some result after execution.
If what I want to do is not possible using higher order function, can you give me a hint what else can I do get something like I described above?
Upvotes: 3
Views: 1794
Reputation: 17829
Whatever you are asking is against the Android best practices. May be mistakenly you have mentioned it in question. You want a function to execute Higher order function in a background thread and (pay attention here) return the value immediately (means block the calling thread until background task is completed).
As you must be knowing that network call should be async call and for that you have to pass an interface to the async method as parameter so that you can be notified when your Higher order function completed it's execution.
And the better option is to use Coroutines a really good alternative for scheduling task in background.
So your given code can be converted like:
async {
var result = bean.createNewUser(User("","","Gosia","gosiak@gmail.com","pass"))
// do whatever you want to do with result here
}
for using Coroutines, you have to add following line in module level gradle file:
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:0.21.2'
Note: Coroutines are in experimental phase now, it might change.
Another option using doAsync from kotlin anko library that is fairly simple and easy to use.
Example:
doAsync {
var result = bean.createNewUser(User("","","Gosia","gosiak@gmail.com","pass"))
// use result here to to further background task
uiThread {
// use result here if you want to update ui
}
}
for using doAsync add following line in module level gradle file:
compile "org.jetbrains.anko:anko-commons:0.10.0"
To read more for doAsync click here.
Hope it helps. Let me know if you have further questions.
Upvotes: 2