繁体   English   中英

如何观察viewmodel中的数据 LiveData + Courotine + MVVM + Retrofit

[英]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)
            }
        }

它不工作。 你能告诉我我做错了什么吗? 谢谢

因为没有在我看来,那你为什么没有得到结果的原因是ObserversLiveData返回由authRepository.login(username, password)

您需要执行以下操作:

val result = authRepository.login(username, password)
result.observe(someLifeCycleOwner, Observer {...})

这通常发生在LifeCyclerOwnersFragmentActivity中。

此外, 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM