简体   繁体   English

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

[英]How to observe data in viewmodel LiveData + Courotine + MVVM + Retrofit

The problem is I could not get the response using LiveData and Courotine in the viewModel.问题是我无法在 viewModel 中使用 LiveData 和 Courotine 获得响应。 Possibly I do not know the right way to do that.可能我不知道这样做的正确方法。 The call is电话是

interface AuthApiService {
    @POST("v2/5e3cba6a2d00008709d958d0")
    @FormUrlEncoded
    suspend fun login(
        @Field("username") username: String,
        @Field("password") password: String
    ): Response<AuthToken>
}

The repository is存储库是

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))
        }
    }
}

What I am trying to do in viewmodel is,我想在视图模型中做的是,

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)
            }
        }

And its not working.它不工作。 Could you please tell me what I am doing wrong?你能告诉我我做错了什么吗? Thanks谢谢

It seems to me that the reason why you are not getting the result is because there are no Observers for the LiveData returned by authRepository.login(username, password)因为没有在我看来,那你为什么没有得到结果的原因是ObserversLiveData返回由authRepository.login(username, password)

You need to do something like:您需要执行以下操作:

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

This usually happens inside a Fragment or Activity which are LifeCyclerOwners .这通常发生在LifeCyclerOwnersFragmentActivity中。

Also, liveData {...} takes a suspend block, but it is not itself a suspend function.此外, liveData {...}需要一个suspend块,但它本身不是suspend函数。 This means that login() does not need to be a suspend function.这意味着login()不需要是suspend函数。

Check below code for architecture using MVVM + Koin [ https://github.com/parthpatibandha/MvvmCleanKotlin ]使用 MVVM + Koin [ https://github.com/parthpatibandha/MvvmCleanKotlin ] 检查下面的架构代码

Retrofit interface改造界面

interface MovieApiService {
    @POST(ApiConstant.API_MOVIES)
    fun getAllMovieList(
        @Query("page") page : String
    ): Deferred<FlickerImageListRS>
}

Repository存储库

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))
    }
}

ViewModel视图模型

class MovieListingViewModel constructor(private val homeRepo: HomeRepo) : BaseViewModel() {

    val movieListRSLiveData: MutableLiveData<FlickerImageListRS> = MutableLiveData()
    fun getMovieList(page : String) {
        launch {
            postValue(homeRepo.getAllMovieList(FlickerImageListPRQ(page)), movieListRSLiveData)
        }
    }

Hope it helps you for understand MVVM with Koin.希望它可以帮助您了解 Koin 的 MVVM。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 ViewModel 中观察 LiveData? - How to observe on LiveData in ViewModel? 如何使用 MVVM 观察发射的 LiveData - How to observe Emited LiveData with MVVM 如何在 DialogFragment 中观察 ViewModel LiveData? - How to observe ViewModel LiveData in a DialogFragment? 无法观察空数据-具有Livedata的MVVM - Cannot observe null data - MVVM with Livedata 如何在 MVVM 架构中观察 RecyclerView 适配器中的 LiveData? - How to observe LiveData in RecyclerView adapter in MVVM architecture? 如何在viewModel中永久删除liveData观察 - How to remove liveData forever observe in viewModel 如何让 EditText 在不使用数据绑定的情况下观察 ViewModel 的 LiveData 并将用户输入转发到 ViewModel - How to make EditText observe a ViewModel's LiveData and forward user input to the ViewModel without using data binding 如何将ViewModel与存储库连接,以便将数据传播到视图(MVVM,Livedata) - How to connect ViewModel with Repository so that data is propagated to the View (MVVM, Livedata) ViewModel中的LiveData如何使用转换观察存储库中的Livedata? - How can LiveData in ViewModel observe the Livedata in Repository using Transformations? Android ViewModel LiveData 观察 - Android ViewModel LiveData observe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM