У меня есть метод наблюдения , который устанавливает цепочку сбора потоков, чтобы реагировать на изменения в моем состоянии пользовательского интерфейса:
private val _uiState = MutableStateFlow(AppUiState.default())
val uiState = _uiState.asStateFlow()
init {
fetchSectionA()
}
private fun fetchSectionA() {
observeAndUpdate(
section = AppSection.SECTION_A,
getData = { someRepo.getData() }
)
}
fun refreshSections() {
viewModelScope.launch(ioDispatcher) {
val order = runCatching { repo.getSectionsOrder() }.getOrElse { AppSection.entries }
val f = _uiState.updateAndGet { it.copy(sections = order) }
println("XXXXXXXXXXX refreshSections: ${f.sections}") // Prints the new sections
}
}
private inline fun observeAndUpdate(
section: AppSection,
noinline getData: suspend (P) -> Flow,
noinline showWhen: (P) -> Boolean = { true },
noinline refreshData: (suspend (P) -> Unit)? = null,
crossinline selector: (AppUiState) -> P = { Unit as P },
) {
uiState.mapLatest { st -> selector(st).let { it to ((section in st.sections) && showWhen(it)) } }
.distinctUntilChanged()
.onEach { (p, s) -> if (s) refreshData?.let { viewModelScope.launch(ioDispatcher) { it(p) } } }
.flatMapLatest { (p, s) -> if (s) flow { emitAll(getData(p)) }.flowOn(ioDispatcher) else flowOf(emptyList()) }
.onEach { updateSection(section, if (it.isEmpty()) Hidden else Success(it)) }
.catch { e -> updateSection(section, Error(e)) }
.launchIn(viewModelScope)
}
< / Code>
p> sets: < / p>
data class AppUiState(
val sections: List,
val lorem1: String,
val lorem2: String,
val lorem3: String,
) {
companion object {
fun default(): AppUiState {
return AppUiState(
sections = AppSection.entries,
lorem1 = "1",
lorem2 = "2",
lorem3 = "3",
)
}
}
}
< /code>
В моем тесте я обновляю разделы несколько раз: < /p>
@Test
fun test_flow_collection() = runTest {
val viewModel = MyViewModel()
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
vm.uiState.collect {
println("Collected state with sections: ${it.sections}")
}
}
// Initial state
viewModel.refreshSections(listOf(AppSection.SECTION_A))
advanceTimeBy(100)
// Change sections - should trigger mapLatest again
viewModel.refreshSections(emptyList())
advanceTimeBy(100)
// Change sections again - should trigger mapLatest again
viewModel.refreshSections(listOf(AppSection.SECTION_A, AppSection.SECTION_B))
advanceTimeBy(100)
}
Журналы показывают, что, хотя uistate обновляется правильно, оператор Maplatest только один раз запускает только один раз для первого излучения, а затем прекращает реагировать на новые выбросы.
Refreshing sections: [SECTION_A]
mapLatest called with sections: [SECTION_A]
Collected state with sections: [SECTION_A]
Refreshing sections: []
Collected state with sections: [] // State updated but mapLatest not called
Refreshing sections: [SECTION_A, SECTION_B]
Collected state with sections: [SECTION_A, SECTION_B] // State updated but mapLatest not called
< /code>
Обратите внимание, что когда я работаю на реальном устройстве Android, это не воспроизводимо. < /p>
Вот мое правило теста: < /p>
class MainDispatcherRule(val testDispatcher: TestDispatcher = UnconfinedTestDispatcher()) : TestWatcher() {
override fun starting(description: Description?) {
super.starting(description)
Dispatchers.setMain(testDispatcher)
}
override fun finished(description: Description?) {
super.finished(description)
Dispatchers.resetMain()
}
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... vironments
Stateflow.maplatest, вызванный только один раз в тестовых средах ⇐ Android
Форум для тех, кто программирует под Android
-
Anonymous
1746605432
Anonymous
У меня есть метод наблюдения , который устанавливает цепочку сбора потоков, чтобы реагировать на изменения в моем состоянии пользовательского интерфейса:
private val _uiState = MutableStateFlow(AppUiState.default())
val uiState = _uiState.asStateFlow()
init {
fetchSectionA()
}
private fun fetchSectionA() {
observeAndUpdate(
section = AppSection.SECTION_A,
getData = { someRepo.getData() }
)
}
fun refreshSections() {
viewModelScope.launch(ioDispatcher) {
val order = runCatching { repo.getSectionsOrder() }.getOrElse { AppSection.entries }
val f = _uiState.updateAndGet { it.copy(sections = order) }
println("XXXXXXXXXXX refreshSections: ${f.sections}") // Prints the new sections
}
}
private inline fun observeAndUpdate(
section: AppSection,
noinline getData: suspend (P) -> Flow,
noinline showWhen: (P) -> Boolean = { true },
noinline refreshData: (suspend (P) -> Unit)? = null,
crossinline selector: (AppUiState) -> P = { Unit as P },
) {
uiState.mapLatest { st -> selector(st).let { it to ((section in st.sections) && showWhen(it)) } }
.distinctUntilChanged()
.onEach { (p, s) -> if (s) refreshData?.let { viewModelScope.launch(ioDispatcher) { it(p) } } }
.flatMapLatest { (p, s) -> if (s) flow { emitAll(getData(p)) }.flowOn(ioDispatcher) else flowOf(emptyList()) }
.onEach { updateSection(section, if (it.isEmpty()) Hidden else Success(it)) }
.catch { e -> updateSection(section, Error(e)) }
.launchIn(viewModelScope)
}
< / Code>
p> sets: < / p>
data class AppUiState(
val sections: List,
val lorem1: String,
val lorem2: String,
val lorem3: String,
) {
companion object {
fun default(): AppUiState {
return AppUiState(
sections = AppSection.entries,
lorem1 = "1",
lorem2 = "2",
lorem3 = "3",
)
}
}
}
< /code>
В моем тесте я обновляю разделы несколько раз: < /p>
@Test
fun test_flow_collection() = runTest {
val viewModel = MyViewModel()
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
vm.uiState.collect {
println("Collected state with sections: ${it.sections}")
}
}
// Initial state
viewModel.refreshSections(listOf(AppSection.SECTION_A))
advanceTimeBy(100)
// Change sections - should trigger mapLatest again
viewModel.refreshSections(emptyList())
advanceTimeBy(100)
// Change sections again - should trigger mapLatest again
viewModel.refreshSections(listOf(AppSection.SECTION_A, AppSection.SECTION_B))
advanceTimeBy(100)
}
Журналы показывают, что, хотя uistate обновляется правильно, оператор Maplatest только один раз запускает только один раз для первого излучения, а затем прекращает реагировать на новые выбросы.
Refreshing sections: [SECTION_A]
mapLatest called with sections: [SECTION_A]
Collected state with sections: [SECTION_A]
Refreshing sections: []
Collected state with sections: [] // State updated but mapLatest not called
Refreshing sections: [SECTION_A, SECTION_B]
Collected state with sections: [SECTION_A, SECTION_B] // State updated but mapLatest not called
< /code>
Обратите внимание, что когда я работаю на реальном устройстве Android, это не воспроизводимо. < /p>
Вот мое правило теста: < /p>
class MainDispatcherRule(val testDispatcher: TestDispatcher = UnconfinedTestDispatcher()) : TestWatcher() {
override fun starting(description: Description?) {
super.starting(description)
Dispatchers.setMain(testDispatcher)
}
override fun finished(description: Description?) {
super.finished(description)
Dispatchers.resetMain()
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79608490/stateflow-maplatest-only-called-once-in-test-environments[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия