File tree Expand file tree Collapse file tree 2 files changed +18
-20
lines changed
app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/usecases/flow/usecase1 Expand file tree Collapse file tree 2 files changed +18
-20
lines changed Original file line number Diff line number Diff line change 11package com.lukaslechner.coroutineusecasesonandroid.usecases.flow.usecase1
22
3- import androidx.lifecycle.MutableLiveData
4- import androidx.lifecycle.viewModelScope
3+ import androidx.lifecycle.LiveData
4+ import androidx.lifecycle.asLiveData
55import com.lukaslechner.coroutineusecasesonandroid.base.BaseViewModel
6- import kotlinx.coroutines.flow.launchIn
76import kotlinx.coroutines.flow.map
8- import kotlinx.coroutines.flow.onEach
7+ import kotlinx.coroutines.flow.onCompletion
98import kotlinx.coroutines.flow.onStart
9+ import timber.log.Timber
1010
1111class FlowUseCase1ViewModel (
1212 stockPriceDataSource : StockPriceDataSource
1313) : BaseViewModel<UiState>() {
1414
15- val currentStockPriceAsLiveData: MutableLiveData <UiState > = MutableLiveData ()
16-
17- init {
18- stockPriceDataSource
19- .latestStockList
20- .map { stockList ->
21- UiState .Success (stockList) as UiState
22- }
23- .onStart {
24- emit(UiState .Loading )
25- }
26- .onEach { uiState ->
27- currentStockPriceAsLiveData.value = uiState
28- }
29- .launchIn(viewModelScope)
30- }
15+ val currentStockPriceAsLiveData: LiveData <UiState > = stockPriceDataSource
16+ .latestStockList
17+ .map { stockList ->
18+ UiState .Success (stockList) as UiState
19+ }
20+ .onStart {
21+ emit(UiState .Loading )
22+ }
23+ .onCompletion {
24+ Timber .tag(" Flow" ).d(" Flow has completed." )
25+ }
26+ .asLiveData()
3127}
Original file line number Diff line number Diff line change @@ -5,6 +5,7 @@ import com.lukaslechner.coroutineusecasesonandroid.usecases.flow.mock.Stock
55import kotlinx.coroutines.delay
66import kotlinx.coroutines.flow.Flow
77import kotlinx.coroutines.flow.flow
8+ import timber.log.Timber
89
910interface StockPriceDataSource {
1011 val latestStockList: Flow <List <Stock >>
@@ -14,6 +15,7 @@ class NetworkStockPriceDataSource(mockApi: FlowMockApi) : StockPriceDataSource {
1415
1516 override val latestStockList: Flow <List <Stock >> = flow {
1617 while (true ) {
18+ Timber .tag(" Flow" ).d(" Fetching current stock prices" )
1719 val currentStockList = mockApi.getCurrentStockPrices()
1820 emit(currentStockList)
1921 delay(5_000 )
You can’t perform that action at this time.
0 commit comments