-
Notifications
You must be signed in to change notification settings - Fork 128
/
EmitAllViewModel.kt
52 lines (45 loc) · 1.65 KB
/
EmitAllViewModel.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
package com.mindorks.kotlinFlow.learn.errorhandling.emitall
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mindorks.kotlinFlow.data.api.ApiHelper
import com.mindorks.kotlinFlow.data.local.DatabaseHelper
import com.mindorks.kotlinFlow.data.model.ApiUser
import com.mindorks.kotlinFlow.utils.Resource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
class EmitAllViewModel(
private val apiHelper: ApiHelper,
private val dbHelper: DatabaseHelper
) : ViewModel() {
private val users = MutableLiveData<Resource<List<ApiUser>>>()
init {
fetchUsers()
}
private fun fetchUsers() {
viewModelScope.launch {
users.postValue(Resource.loading(null))
apiHelper.getUsers()
.zip(
apiHelper.getUsersWithError()
.catch { emitAll(flowOf(emptyList())) }) { usersFromApi, moreUsersFromApi ->
val allUsersFromApi = mutableListOf<ApiUser>()
allUsersFromApi.addAll(usersFromApi)
allUsersFromApi.addAll(moreUsersFromApi)
return@zip allUsersFromApi
}
.flowOn(Dispatchers.Default)
.catch { e ->
users.postValue(Resource.error(e.toString(), null))
}
.collect {
users.postValue(Resource.success(it))
}
}
}
fun getUsers(): LiveData<Resource<List<ApiUser>>> {
return users
}
}