I'm new using Kotlin as language, and I'm making a simple app in Android Studio just to learn the language. However I can't find a proper answer to this question.
I have a function (code scraped from some places and based on the default LoginActivity from Android Studio) which returns a 'Unit'
class LoginDataSource {
private val client = OkHttpClient()
fun login(username: String, password: String, then: ((Result<LoggedInUser>) -> Unit)) {
try {
val formBody = FormBody.Builder()
.add("username", username)
.add("password", password)
.build()
val request = Request.Builder()
.url("https://api.url")
.post(formBody)
.build();
client.newCall(request).enqueue(object: Callback {
override fun onResponse(call: Call, response: Response) {
println("RESULT FROM HTTP CALL: ${response.code}: ${response.message}")
val body = response?.body?.string()
//Need the body here, but no code for now exists, (not the scope of this question)
val fakeUser = LoggedInUser(java.util.UUID.randomUUID().toString(), "Jane Doe", "1234")
then(Result.Success(fakeUser))
}
override fun onFailure(call: Call, e: IOException) {
Result.Error(IOException("Error logging in: ${e.message}"))
then(Result.Error(e))
}
})
} catch (e: Throwable) {
then(Result.Error(IOException("Error logging in", e)))
}
}
}
this code returns then(Result.Success(user)
Now I want to call this function, so I assume I need to do something like this:
dataSource.login(username, password) {
if (result is Result.Success) {
setLoggedInUser(result.data)
}
return result
}
But that gives the error 'No value passed for parameter 'then'. So I need to add 'then' as parameter in the function call, but I can't find how to do that. Can you give me an example for this? The way I call the function this way to avoid 'running to may tasks on the main thread' which is also hard to prevent/solve when you are new with this.