@@ -6,12 +6,12 @@ import com.fuusy.common.network.DataState
6
6
import com.fuusy.common.network.ResState
7
7
import com.fuusy.common.network.net.StateLiveData
8
8
import kotlinx.coroutines.CoroutineScope
9
+ import kotlinx.coroutines.Dispatchers
9
10
import kotlinx.coroutines.coroutineScope
11
+ import kotlinx.coroutines.flow.*
10
12
import java.io.IOException
11
13
12
14
13
- private const val TAG = " BaseRepository"
14
-
15
15
/* *
16
16
* @date:2021/5/20
17
17
* @author fuusy
@@ -20,11 +20,65 @@ private const val TAG = "BaseRepository"
20
20
*/
21
21
open class BaseRepository {
22
22
23
+ companion object {
24
+ private const val TAG = " BaseRepository"
25
+ }
26
+
27
+ /* *
28
+ * 方式二:结合Flow请求数据。
29
+ * 根据Flow的不同请求状态,如onStart、onEmpty、onCompletion等设置baseResp.dataState状态值,
30
+ * 最后通过stateLiveData分发给UI层。
31
+ *
32
+ * @param block api的请求方法
33
+ * @param stateLiveData 每个请求传入相应的LiveData,主要负责网络状态的监听
34
+ */
35
+ suspend fun <T : Any > executeReqWithFlow (
36
+ block : suspend () -> BaseResp <T >,
37
+ stateLiveData : StateLiveData <T >
38
+ ) {
39
+ var baseResp = BaseResp <T >()
40
+ flow {
41
+ val respResult = block.invoke()
42
+ baseResp = respResult
43
+ Log .d(TAG , " executeReqWithFlow: $baseResp " )
44
+ baseResp.dataState = DataState .STATE_SUCCESS
45
+ stateLiveData.postValue(baseResp)
46
+ emit(respResult)
47
+ }
48
+ .flowOn(Dispatchers .IO )
49
+ .onStart {
50
+ Log .d(TAG , " executeReqWithFlow:onStart" )
51
+ baseResp.dataState = DataState .STATE_LOADING
52
+ stateLiveData.postValue(baseResp)
53
+ }
54
+ .onEmpty {
55
+ Log .d(TAG , " executeReqWithFlow:onEmpty" )
56
+ baseResp.dataState = DataState .STATE_EMPTY
57
+ stateLiveData.postValue(baseResp)
58
+ }
59
+ .catch { exception ->
60
+ run {
61
+ Log .d(TAG , " executeReqWithFlow:code ${baseResp.errorCode} " )
62
+ exception.printStackTrace()
63
+ baseResp.dataState = DataState .STATE_ERROR
64
+ baseResp.error = exception
65
+ stateLiveData.postValue(baseResp)
66
+ }
67
+ }
68
+ .collect {
69
+ Log .d(TAG , " executeReqWithFlow: collect" )
70
+ stateLiveData.postValue(baseResp)
71
+ }
72
+
73
+
74
+ }
75
+
23
76
/* *
77
+ * 方式一
24
78
* repo 请求数据的公共方法,
25
79
* 在不同状态下先设置 baseResp.dataState的值,最后将dataState 的状态通知给UI
26
- * @param api的请求方法
27
- * @param 每个请求传入相应的LiveData,主要负责网络状态的监听
80
+ * @param block api的请求方法
81
+ * @param stateLiveData 每个请求传入相应的LiveData,主要负责网络状态的监听
28
82
*/
29
83
suspend fun <T : Any > executeResp (
30
84
block : suspend () -> BaseResp <T >,
@@ -63,8 +117,7 @@ open class BaseRepository {
63
117
64
118
65
119
/* *
66
- * @deprecated Use {@link executeResp}
67
- * instead.
120
+ * @deprecated Use {@link executeResp} instead.
68
121
*/
69
122
suspend fun <T : Any > executeResp (
70
123
resp : BaseResp <T >,
0 commit comments