Code: Select all
class YourRepository {
private var counter = 0
fun getDataStream(): Flow = flow {
while (true) {
counter++
val newData = YourDataClass(
info = "Update #$counter",
timestamp = System.currentTimeMillis()
)
emit(newData)
delay(5000)
}
}
}
- Mit flatMapLatest
Code: Select all
class YourViewModel(
private val repository: YourRepository
) : ViewModel() {
// StateFlow for the UI
val uiState: StateFlow = repository
.getDataStream()
.flatMapLatest { data ->
flow {
emit(null) // Show loading initially
delay(2000) // Wait 2 seconds
emit(data) // Show actual data
}
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = null
)
}
- Transfrom verwenden
Code: Select all
class YourViewModel(
private val repository: YourRepository,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) : ViewModel() {
val uiState: StateFlow = repository.getDataStream()
.transform { newData ->
emit(DataUiState.Updating)
delay(2000)
emit(DataUiState.Success(newData))
}
.flowOn(ioDispatcher)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = DataUiState.InitialLoading
)
}
Mobile version