-
Notifications
You must be signed in to change notification settings - Fork 418
/
FlowUseCase2ViewModel.kt
73 lines (66 loc) 路 2.56 KB
/
FlowUseCase2ViewModel.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.lukaslechner.coroutineusecasesonandroid.usecases.flow.usecase2
import androidx.lifecycle.LiveData
import androidx.lifecycle.asLiveData
import com.lukaslechner.coroutineusecasesonandroid.base.BaseViewModel
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.*
import timber.log.Timber
class FlowUseCase2ViewModel(
stockPriceDataSource: StockPriceDataSource,
defaultDispatcher: CoroutineDispatcher
) : BaseViewModel<UiState>() {
/*
Flow exercise 1 Goals
1) only update stock list when Alphabet(Google) (stock.name ="Alphabet (Google)") stock price is > 2300$
2) only show stocks of "United States" (stock.country == "United States")
3) show the correct rank (stock.rank) within "United States", not the world wide rank
4) filter out Apple (stock.name ="Apple") and Microsoft (stock.name ="Microsoft"), so that Google is number one
5) only show company if it is one of the biggest 10 companies of the "United States" (stock.rank <= 10)
6) stop flow collection after 10 emissions from the dataSource
7) log out the number of the current emission so that we can check if flow collection stops after exactly 10 emissions
8) Perform all flow processing on a background thread
*/
val currentStockPriceAsLiveData: LiveData<UiState> = stockPriceDataSource
.latestStockList
.withIndex()
.onEach { indexedValue ->
Timber.d("Processing emission ${indexedValue.index + 1}")
}
.map { indexedValue ->
indexedValue.value
}
.take(10)
.filter { stockList ->
val googlePrice = stockList.find { stock ->
stock.name == "Alphabet (Google)"
}?.currentPrice ?: return@filter false
googlePrice > 2300
}
.map { stockList ->
stockList.filter { stock ->
stock.country == "United States"
}
}
.map { stockList ->
stockList.filter { stock ->
stock.name != "Apple" && stock.name != "Microsoft"
}
}
.map { stockList ->
stockList.mapIndexed { index, stock ->
stock.copy(rank = index + 1)
}
}
.map { stockList ->
stockList.filter { stock ->
stock.rank <= 10
}
}
.map { stockList ->
UiState.Success(stockList) as UiState
}
.onStart {
emit(UiState.Loading)
}
.asLiveData(defaultDispatcher)
}