Home > front end >  Creating a LiveData class for my ViewModel class and Retrofit class
Creating a LiveData class for my ViewModel class and Retrofit class

Time:10-08

I'm struggling with creating a LiveData class for my ViewModel class and my Retrofit class that makes API calls.

ViewModel class:

class ApiViewModel : ViewModel() {

    private lateinit var status: String

    @NonNull
    fun getApiResults(param1: String, param2: String, param3: String) {
        viewModelScope.launch {
            try {
                val listResult = ApiCalls.retrofitService.ApiCallsService(param1, param2, param3)
            } catch (e: Exception) {
                status = "Failure: ${e.message}"
            }
        }
    }
}

Retrofit class:

private const val BASE_URL = "https://sampleapiurl.com"

private val moshi = Moshi.Builder().addLast(KotlinJsonAdapterFactory()).build()

private val client = OkHttpClient.Builder()
    .connectTimeout(60, TimeUnit.SECONDS)
    .writeTimeout(60, TimeUnit.SECONDS)
    .readTimeout(60, TimeUnit.SECONDS)
    .build()

private val retrofit = Retrofit.Builder()
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    .baseUrl(BASE_URL)
    .client(client)
    .build()

interface ApiCallsService {
    @GET(".")
    suspend fun apiCalls(
        @Query("param1") param1: String,
        @Query("param2") param2: String,
        @Query("param3") param3: String
    ): Call<CustomDataClass>
}

object ApiCalls {
    val retrofitService: ApiCallsService by lazy { retrofit.create(ApiCallsService::class.java) }
}

Now, inside the try catch statement in my ViewModel class, I want to pass the result of listResult into a LiveData class. That way in my onViewCreated in my fragments, I can do something like this to retrieve the data:

val apiViewModel = ViewModelProvider(this).get(ApiViewModel::class.java)
apiViewModel.getApiResults("val1", "val2", "val3").observe(...

How should my LiveData class look so I can achieve this?

CodePudding user response:

You may need to create LiveData to observe any values you desired. In your case, seems you need to observe the value of status and listResult. Therefore, I suggest you create LiveData in ApiViewModel, i.e.

val statusLiveData = MutableLiveData<String>()
val listResultLiveData = MutableLiveData<YourListType>()

and post value to it in your getApiResults() (modify your getApiResults())

@NonNull
fun getApiResults(param1: String, param2: String, param3: String) {
     viewModelScope.launch {
         try {
           listResultLiveData.postValue(ApiCalls.retrofitService.ApiCallsService(param1, param2, param3))
         } catch (e: Exception) {
            statusLiveData.postValue("Failure: ${e.message}")
         }
     }
}

and add this to onViewCreated() in the Fragment

apiViewModel.statusLiveData.observe(viewLifecycleOwner, Observer { 
   // TODO: What to do with the status            
})
apiViewModel.listResultLiveData.observe(viewLifecycleOwner, Observer { 
   // TODO: What to do on get list result            
})
  • Related