-
Notifications
You must be signed in to change notification settings - Fork 0
/
NetworkBoundResourceMVI.kt
59 lines (47 loc) · 1.8 KB
/
NetworkBoundResourceMVI.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
package com.anikinkirill.mviplayground.repository
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import com.anikinkirill.mviplayground.api.ApiResponse
import com.anikinkirill.mviplayground.api.ApiResponse.*
import com.anikinkirill.mviplayground.util.DataState
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
abstract class NetworkBoundResourceMVI<ResultObject, ViewStateType> {
protected val result = MediatorLiveData<DataState<ViewStateType>>()
init {
result.value = DataState.loading(true)
GlobalScope.launch(IO) {
delay(2000L)
withContext(Main) {
val apiResponse = createCall()
result.addSource(apiResponse) { response ->
result.removeSource(apiResponse)
handleNetworkCall(response)
}
}
}
}
private fun handleNetworkCall(response: ApiResponse<ResultObject>) {
when(response) {
is ApiSuccessResponse -> {
handleApiSuccessResponse(response)
}
is ApiErrorResponse -> {
onErrorResponse(response.errorMessage)
}
is ApiEmptyResponse -> {
onErrorResponse("Empty Response!")
}
}
}
private fun onErrorResponse(message: String) {
result.value = DataState.error(message)
}
abstract fun handleApiSuccessResponse(response: ApiSuccessResponse<ResultObject>)
abstract fun createCall() : LiveData<ApiResponse<ResultObject>>
fun asLiveData() = result
}