https://kotlinlang.org logo
o

Ofir Bar

03/11/2020, 11:22 AM
Source:
Copy code
class MyPublishedAdvertisementsViewModel(private val advertisementRepository : AdvertisementRepository) : ViewModel(){

    var _myPublishedAdvertisements : MutableLiveData<NetworkCall<MyPublishedAdvertisementsResponse>> = MutableLiveData()
    val myPublishedAdvertisements : LiveData< NetworkCall<MyPublishedAdvertisementsResponse> > = _myPublishedAdvertisements

    // Called every time our UI is #onStarted
    fun getFreshData(){
        _myPublishedAdvertisements.value = liveData {
            emit(NetworkCall<MyPublishedAdvertisementsResponse>(NetworkStatus.LOADING, null, ""))
            val publishedAdvertisements = advertisementRepository.getMyPublishedAdvertisements()
            emit(publishedAdvertisements)
        }
    }

}
k

Kirill Prybylsky

03/11/2020, 11:24 AM
Does your NetworkCall extends LiveData?
o

Ofir Bar

03/11/2020, 11:26 AM
No
It is a wrapper data class to be used for all my network responses, this is the code:
Copy code
data class NetworkCall<out T>(val status: NetworkStatus, val data: T?, val message: String?) {

    companion object {
        fun <T> success(data: T?): NetworkCall<T> {
            return NetworkCall(NetworkStatus.SUCCESS, data, null)
        }

        fun <T> error(msg: String, data: T?): NetworkCall<T> {
            return NetworkCall(NetworkStatus.ERROR, data, msg)
        }

        fun <T> loading(data: T?): NetworkCall<T> {
            return NetworkCall(NetworkStatus.LOADING, data, null)
        }
    }

}
k

Kirill Prybylsky

03/11/2020, 11:27 AM
But you’re putting liveData{} as a value of another live data
o

Ofir Bar

03/11/2020, 11:29 AM
I am not sure what I am doing wrong 🤔
k

Kirill Prybylsky

03/11/2020, 11:32 AM
Seems like you are doing this, isn’t?
o

Ofir Bar

03/11/2020, 11:35 AM
Ohhhh, ok I got what you’re saying But I still don’t understand how I use liveData{} to change the values of a MutableLiveData. Why for LiveData I can use liveData{}, and for MutableLiveData I can’t?
k

Kirill Prybylsky

03/11/2020, 11:40 AM
For my opinion you are trying to achieve something completely wrong. You should rethink this code. Also, there shouldn’t be any network requests from your view model class this is bad practice.
o

Ofir Bar

03/11/2020, 11:54 AM
I will check thanks for the help anyway @Kirill Prybylsky
12 Views