Android kotlin coroutine retrofit.
I want to get the value from the getPropeties to insert it in database. I Need a help for this? I need the value to be an instance of User not the unit value. My viewModel class is given below.
import android.app.Application
import android.content.Context
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.android.marsrealestate.database.AppDatabase
import com.example.android.marsrealestate.database.User
import com.example.android.marsrealestate.database.UserDao
import com.example.android.marsrealestate.network.UsersApi
import com.example.android.marsrealestate.network.UsersProperty
import kotlinx.coroutines.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class OverviewViewModel(val database: UserDao,
application: Application): ViewModel() {
private var viewModelJob = Job()
private val coroutineScope = CoroutineScope(
viewModelJob + Dispatchers.Main )
private var user = MutableLiveData<User?>()
// The internal MutableLiveData String that stores the most recent response
private val _response = MutableLiveData<String>()
// The external immutable LiveData for the response String
val response: LiveData<String>
get() = _response
init {
getUsersProperties()
}
private fun getUsersProperties(){
coroutineScope.launch {
var getPropertiesDeferred =
UsersApi.retrofitService.getProperties()
try {
var listResult = getPropertiesDeferred.await()
//database.insertUser(listResult)
_response.value =
"Success: ${listResult} Mars properties retrieved"
} catch (e: Exception) {
_response.value = "Failure: ${e.message}"
}
}
}
override fun onCleared() {
super.onCleared()
viewModelJob.cancel()
}
}
Thanks
You are using launch
,
Launch is used to perform asynchronous fire and forget type of operations where you are not interested in the result of operation.
Instead, you can use async
,
Async is used to perform asynchronous computation where you expect a result of the computation in the future
private fun getUsersProperties() =
coroutineScope.async {
var getPropertiesDeferred =
UsersApi.retrofitService.getProperties()
try {
var listResult = getPropertiesDeferred.await()
//database.insertUser(listResult)
_response.value =
"Success: ${listResult} Mars properties retrieved"
} catch (e: Exception) {
_response.value = "Failure: ${e.message}"
}
// =================================================
// ========= Return whatever result you want =======
// =================================================
}
can you also show what is the type signature of getProperties
?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.