-
Notifications
You must be signed in to change notification settings - Fork 411
/
FlowUseCase3ViewModel.kt
46 lines (40 loc) 路 1.47 KB
/
FlowUseCase3ViewModel.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
package com.lukaslechner.coroutineusecasesonandroid.usecases.flow.usecase3
import androidx.lifecycle.LiveData
import androidx.lifecycle.asLiveData
import com.lukaslechner.coroutineusecasesonandroid.base.BaseViewModel
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import timber.log.Timber
class FlowUseCase3ViewModel(
stockPriceDataSource: StockPriceDataSource
) : BaseViewModel<UiState>() {
/*
Exercise: Flow Exception Handling
Tasks:
- Adjust code in StockPriceDataSource and FlowUseCase3ViewModel
Exception Handling Goals:
- for HttpExceptions in the datasource
- re-collect from the flow
- delay for 5 seconds before re-collecting the flow
- for all other Exceptions within the whole flow pipeline
- show toast with error message by emitting UiState.Error
*/
val currentStockPriceAsLiveData: LiveData<UiState> = stockPriceDataSource
.latestStockList
.map { stockList ->
UiState.Success(stockList) as UiState
}
.onStart {
emit(UiState.Loading)
}
.onCompletion {
Timber.tag("Flow").d("Flow has completed.")
}
.catch { throwable ->
Timber.tag("Flow").d("Enter catch operator with $throwable")
emit(UiState.Error("something went wrong"))
}
.asLiveData()
}