无法通过 Retrofit Coroutine api 调用获得响应
Unable to get response with Retrofit Coroutine api call
我正在尝试从 api 获取对实时数据的响应,但没有使用此代码调用请求。
class AuthActivityViewModel : ViewModel() {
var authResp: LiveData<ObjAuthResp> = MutableLiveData()
val repository = BaseRepository()
fun login(username: String, password: String) {
authResp = liveData(Dispatchers.IO) {
val resp = repository.login(username, password)
emit(resp)
}
}
}
但它适用于此代码。
class AuthActivityViewModel : ViewModel() {
val repository = BaseRepository()
var authResp = liveData(Dispatchers.IO) {
val resp = repository.login(username, password)
emit(resp)
}
}
API 服务
@POST("profile/pub/auth/login")
suspend fun login(@Body authReqBody : ObjAuthReqBody): ObjAuthResp
基础资料库
open class BaseRepository {
suspend fun login(username:String,password:String) = service.login(ObjAuthReqBody( username, password))
}
来自 activity
的电话
btn_login.setOnClickListener {
viewModel.login(edt_username.text.toString(),
edt_password.text.toString())
}
回答我自己的问题,
问题出在 authResp = liveData(Dispatchers.IO) {...
行,这是在创建新的 LiveData,而旧观察者在观察初始 var authResp: LiveData<ObjAuthResp> = MutableLiveData()
。因此,由于没有 Observers 监听新创建的 LiveData
,甚至没有进行调用。
此代码有效
var authResp = MutableLiveData<ObjAuthResp>()
fun login(username: String, password: String) {
viewModelScope.launch {
withContext(Dispatchers.IO) {
val resp = repository.login(username, password)
authResp.postValue( resp)
}
}
}
我正在尝试从 api 获取对实时数据的响应,但没有使用此代码调用请求。
class AuthActivityViewModel : ViewModel() {
var authResp: LiveData<ObjAuthResp> = MutableLiveData()
val repository = BaseRepository()
fun login(username: String, password: String) {
authResp = liveData(Dispatchers.IO) {
val resp = repository.login(username, password)
emit(resp)
}
}
}
但它适用于此代码。
class AuthActivityViewModel : ViewModel() {
val repository = BaseRepository()
var authResp = liveData(Dispatchers.IO) {
val resp = repository.login(username, password)
emit(resp)
}
}
API 服务
@POST("profile/pub/auth/login")
suspend fun login(@Body authReqBody : ObjAuthReqBody): ObjAuthResp
基础资料库
open class BaseRepository {
suspend fun login(username:String,password:String) = service.login(ObjAuthReqBody( username, password))
}
来自 activity
的电话 btn_login.setOnClickListener {
viewModel.login(edt_username.text.toString(),
edt_password.text.toString())
}
回答我自己的问题,
问题出在 authResp = liveData(Dispatchers.IO) {...
行,这是在创建新的 LiveData,而旧观察者在观察初始 var authResp: LiveData<ObjAuthResp> = MutableLiveData()
。因此,由于没有 Observers 监听新创建的 LiveData
,甚至没有进行调用。
此代码有效
var authResp = MutableLiveData<ObjAuthResp>()
fun login(username: String, password: String) {
viewModelScope.launch {
withContext(Dispatchers.IO) {
val resp = repository.login(username, password)
authResp.postValue( resp)
}
}
}