[英]How to observe data in viewmodel LiveData + Courotine + MVVM + Retrofit
問題是我無法在 viewModel 中使用 LiveData 和 Courotine 獲得響應。 可能我不知道這樣做的正確方法。 電話是
interface AuthApiService {
@POST("v2/5e3cba6a2d00008709d958d0")
@FormUrlEncoded
suspend fun login(
@Field("username") username: String,
@Field("password") password: String
): Response<AuthToken>
}
存儲庫是
class AuthRepository
@Inject
constructor(
val authApiService: AuthApiService
) {
suspend fun login(username: String, password: String) = liveData {
emit(GenericResult.Loading(null))
try {
emit(GenericResult.Success(authApiService.login(username, password)))
} catch (ioException: Exception) {
emit(GenericResult.Error(ioException))
}
}
}
我想在視圖模型中做的是,
viewModelScope.launch {
val result = authRepository.login(username, password)
when (result.value) {
is GenericResult.Loading -> isLoading.postValue(true)
is GenericResult.Success -> authToken.postValue((result.value as GenericResult.Success<Response<AuthToken>>).data.body())
is GenericResult.Error -> onMessageError.postValue((result.value as GenericResult.Error).exception)
}
}
它不工作。 你能告訴我我做錯了什么嗎? 謝謝
因為沒有在我看來,那你為什么沒有得到結果的原因是Observers
的LiveData
返回由authRepository.login(username, password)
您需要執行以下操作:
val result = authRepository.login(username, password)
result.observe(someLifeCycleOwner, Observer {...})
這通常發生在LifeCyclerOwners
的Fragment
或Activity
中。
此外, liveData {...}
需要一個suspend
塊,但它本身不是suspend
函數。 這意味着login()
不需要是suspend
函數。
使用 MVVM + Koin [ https://github.com/parthpatibandha/MvvmCleanKotlin ] 檢查下面的架構代碼
改造界面
interface MovieApiService {
@POST(ApiConstant.API_MOVIES)
fun getAllMovieList(
@Query("page") page : String
): Deferred<FlickerImageListRS>
}
存儲庫
class HomeRepository constructor(
private val homeLocalDataSource: HomeLocalDataSource,
private val homeRemoteDataSource: HomeRemoteDataSource
) : BaseRepository(), HomeRepo {
override suspend fun getAllMovieList(flickerImageListPRQ: FlickerImageListPRQ): Either<MyAppException, FlickerImageListRS> {
return either(homeRemoteDataSource.getAllMovieList(flickerImageListPRQ))
}
}
視圖模型
class MovieListingViewModel constructor(private val homeRepo: HomeRepo) : BaseViewModel() {
val movieListRSLiveData: MutableLiveData<FlickerImageListRS> = MutableLiveData()
fun getMovieList(page : String) {
launch {
postValue(homeRepo.getAllMovieList(FlickerImageListPRQ(page)), movieListRSLiveData)
}
}
希望它可以幫助您了解 Koin 的 MVVM。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.