代碼 A 來自關于 Flow的官方文章
viewModelScope.launch{}默認在 UI 執行緒中運行,我想suspend fun fetchLatestNews()也會默認在 UI 執行緒中運行,所以我認為 Code A 可能會在fetchLatestNews()長時間運行時導致 UI 阻塞,對吧?
我認為代碼 B 可以解決問題,對吧?
代碼 A
class LatestNewsViewModel(
private val newsRepository: NewsRepository
) : ViewModel() {
init {
viewModelScope.launch {
// Trigger the flow and consume its elements using collect
newsRepository.favoriteLatestNews.collect { favoriteNews ->
// Update View with the latest favorite news
}
}
}
}
class NewsRemoteDataSource(
private val newsApi: NewsApi,
private val refreshIntervalMs: Long = 5000
) {
val latestNews: Flow<List<ArticleHeadline>> = flow {
while(true) {
val latestNews = newsApi.fetchLatestNews()
emit(latestNews) // Emits the result of the request to the flow
delay(refreshIntervalMs) // Suspends the coroutine for some time
}
}
}
// Interface that provides a way to make network requests with suspend functions
interface NewsApi {
suspend fun fetchLatestNews(): List<ArticleHeadline>
}
代碼 B
class LatestNewsViewModel(
private val newsRepository: NewsRepository
) : ViewModel() {
init {
viewModelScope.launch(Dispatchers.IO) {
//The same
}
}
}
//The same
uj5u.com熱心網友回復:
代碼 A 不會阻塞 UI 執行緒,因為該launch方法不會阻塞當前執行緒。
正如檔案所說:
在不阻塞當前執行緒的情況下啟動一個新的協程,并將對該協程的參考作為 [Job] 回傳。
如果背景關系沒有任何調度程式或任何其他 [ContinuationInterceptor],則使用 [Dispatchers.Default]。
因此,在您的情況下, CodeA 使用Dispatches.Default底層,而 CodeB 使用Dispatchers.IO
更多關于協程的資訊在這里
uj5u.com熱心網友回復:
@qki 寫對了。但他的回答不準確。ViewModel 有 viewModelScope。viewModelScope 有背景關系 SuperVisorJob() Dispatchers.Main.immediatly。LatestNewsViewModel 的 init 將在主組執行緒中執行,但這不會阻塞 ui 執行緒。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/422373.html
標籤:
上一篇:為什么當我將歷史物件(它是BOM的一部分)傳遞給Object.getOwnPropertyDescriptors()時它不起作用?
