1
1
package com.pengxh.kt.lib.vm
2
2
3
+ import android.content.Context
3
4
import androidx.lifecycle.MutableLiveData
4
5
import com.google.gson.Gson
5
- import com.google.gson.JsonParser
6
+ import com.google.gson.JsonObject
6
7
import com.google.gson.reflect.TypeToken
7
8
import com.pengxh.kt.lib.model.NewsListModel
8
9
import com.pengxh.kt.lib.utils.RetrofitServiceManager
9
10
import com.pengxh.kt.lite.base.BaseViewModel
10
11
import com.pengxh.kt.lite.extensions.launch
12
+ import com.pengxh.kt.lite.extensions.show
11
13
import com.pengxh.kt.lite.utils.LoadState
12
14
13
15
class HttpRequestViewModel : BaseViewModel () {
14
16
15
- private val kTag = " HttpRequestViewModel"
16
- private val gson = Gson ()
17
+ val gson by lazy { Gson () }
17
18
val httpRequestResult = MutableLiveData <NewsListModel >()
18
19
19
- fun getNewsByPage (channel : String , start : Int ) = launch({
20
+ fun getNewsByPage (context : Context , channel : String , start : Int ) = launch({
20
21
loadState.value = LoadState .Loading
21
22
val response = RetrofitServiceManager .getNewsByPage(channel, start)
22
- when (response.getResponseCode()) {
23
+ val header = response.getResponseHeader()
24
+ when (header.first) {
23
25
0 -> {
24
26
httpRequestResult.value = gson.fromJson<NewsListModel >(
25
27
response, object : TypeToken <NewsListModel >() {}.type
@@ -29,18 +31,20 @@ class HttpRequestViewModel : BaseViewModel() {
29
31
30
32
else -> {
31
33
loadState.value = LoadState .Fail
34
+ header.second.show(context)
32
35
}
33
36
}
34
37
}, {
35
38
loadState.value = LoadState .Fail
36
39
})
37
40
38
- private fun String.getResponseCode (): Int {
41
+ private fun String.getResponseHeader (): Pair < Int , String > {
39
42
if (this .isBlank()) {
40
- return 404
43
+ return Pair ( 404 , " Invalid Response " )
41
44
}
42
- val element = JsonParser .parseString(this )
43
- val jsonObject = element.asJsonObject
44
- return jsonObject.get(" status" ).asInt
45
+ val jsonObject = gson.fromJson(this , JsonObject ::class .java)
46
+ val code = jsonObject.get(" code" ).asInt
47
+ val message = jsonObject.get(" message" ).asString
48
+ return Pair (code, message)
45
49
}
46
50
}
0 commit comments