-
Notifications
You must be signed in to change notification settings - Fork 9
/
RetroCoroutineViewModel.kt
89 lines (57 loc) · 2.27 KB
/
RetroCoroutineViewModel.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.rxretrofit.viewmodel
import androidx.lifecycle.*
import com.rxretrofit.DI.DaggerRetroRxComponent
import com.rxretrofit.model.RetroRxModel
import kotlinx.coroutines.*
import retrofit2.Retrofit
import javax.inject.Inject
class RetroCoroutineViewModel(private val dispatcher: CoroutineDispatcher,private val apiService: APIService) : ViewModel(),LifecycleObserver{
//CoRoutine API Call
private val exceptionHandler = CoroutineExceptionHandler{
_, throwable ->
onError("Exception : ${throwable.localizedMessage}")
}
private val errorOnAPI = MutableLiveData<String>()
private val mutableLiveData:MutableLiveData<List<RetroRxModel>> = MutableLiveData()
var loading : MutableLiveData<Boolean> = MutableLiveData()
/* @Inject
lateinit var retrofit: Retrofit
*/
// lateinit var apiService: APIService
init {
// DaggerRetroRxComponent.create().inject(this)
loading.value = true
// apiService = retrofit.create(APIService::class.java)
}
val postsMutableLiveData:MutableLiveData<List<RetroRxModel>> = MutableLiveData()
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun fetchResponseFromAPI(){
viewModelScope.launch (dispatcher){
// postsMutableLiveData.postValue(null)
try{
val response = apiService.fetchUserPosts()
if(response.isSuccessful){
postsMutableLiveData.postValue(response.body())
loading.postValue(false)
// loading.value = false
}else{
loading.postValue(false)
errorOnAPI.postValue("Something went wrong::${response.message()}")
}
}catch (e:Exception){
loading.postValue(false)
errorOnAPI.postValue("Something went wrong::${e.localizedMessage}")
}
}
}
fun fetchPostLiveData(): LiveData<List<RetroRxModel>> = postsMutableLiveData
override fun onCleared() {
super.onCleared()
}
fun fetchError(): LiveData<String> = errorOnAPI
fun fetchLoadStatus():LiveData<Boolean> = loading
private fun onError(message: String){
errorOnAPI.value = message
loading.value = false
}
}