Android kotlin协程改造。
我想从getPropeties中获取值以将其插入数据库中。我需要帮助吗?我需要该值是User的实例,而不是单位值。我的viewModel类如下。
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()
}
}
谢谢
答案 0 :(得分:0)
您正在使用launch
,
启动用于执行异步触发并忘记类型 对操作结果不感兴趣的操作。
相反,您可以使用async
,
异步用于执行异步计算,如果您期望 未来的计算结果
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 =======
// =================================================
}
您还可以显示getProperties
的类型签名是什么吗?