当前位置: 首页 > news >正文

官方网站下载微博wordpress系统的特点

官方网站下载微博,wordpress系统的特点,深圳 骏域网站建设,flash网站开发文章目录 一 什么是数据流二 创建数据流三 修改数据流四 从数据流中进行收集五 数据流捕获异常六 在不同 CoroutineContext 中执行七 Jetpack 库中的数据流八 将基于回调的 API 转换为数据流 一 什么是数据流 数据流以协程为基础构建,可提供多个值。从概念上来讲&a…

文章目录

    • 一 什么是数据流
    • 二 创建数据流
    • 三 修改数据流
    • 四 从数据流中进行收集
    • 五 数据流捕获异常
    • 六 在不同 CoroutineContext 中执行
    • 七 Jetpack 库中的数据流
    • 八 将基于回调的 API 转换为数据流

一 什么是数据流

数据流以协程为基础构建,可提供多个值。从概念上来讲,数据流是可通过异步方式进行计算处理的一组数据序列

数据流包含三个实体:

  • 提供方会生成添加到数据流中的数据。得益于协程,数据流还可以异步生成数据。
  • (可选)中介可以修改发送到数据流的值,或修正数据流本身。
  • 使用方则使用数据流中的值。

二 创建数据流

如需创建数据流,请使用数据流构建器 API。flow 构建器函数会创建一个新数据流,可使用 emit 函数手动将新值发送到数据流中。

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 flowdelay(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>
}

flow 构建器在协程内执行。因此,它将受益于相同异步 API,但也存在一些限制:

  • 数据流是有序的。当协程内的提供方调用挂起函数时,提供方会挂起,直到挂起函数返回。在此示例中,提供方会挂起,直到 fetchLatestNews 网络请求完成为止。只有这样,请求结果才会发送到数据流中。
  • 使用 flow 构建器时,提供方不能提供来自不同 CoroutineContext 的 emit 值。因此,请勿通过创建新协程或使用 withContext 代码块,在不同 CoroutineContext 中调用 emit。在这些情况下,可使用其他数据流构建器,例如 callbackFlow。

三 修改数据流

中介可以利用中间运算符如map在不使用值的情况下修改数据流。这些运算符都是函数,可在应用于数据流时,设置一系列暂不执行的链式运算,留待将来使用值时执行。

class NewsRepository(private val newsRemoteDataSource: NewsRemoteDataSource,private val userData: UserData
) {/*** Returns the favorite latest news applying transformations on the flow.* These operations are lazy and don't trigger the flow. They just transform* the current value emitted by the flow at that point in time.*/val favoriteLatestNews: Flow<List<ArticleHeadline>> =newsRemoteDataSource.latestNews// Intermediate operation to filter the list of favorite topics.map { news -> news.filter { userData.isFavoriteTopic(it) } }// Intermediate operation to save the latest news in the cache.onEach { news -> saveInCache(news) }
}

四 从数据流中进行收集

使用终端运算符可触发数据流开始监听值。如需获取数据流中的所有发出值,请使用 collect

class LatestNewsViewModel(private val newsRepository: NewsRepository
) : ViewModel() {init {viewModelScope.launch {// Trigger the flow and consume its elements using collectnewsRepository.favoriteLatestNews.collect { favoriteNews ->// Update View with the latest favorite news}}}
}

数据流收集可能会由于以下原因而停止:

  • 如上例所示,协程收集被取消。此操作也会让底层提供方停止活动。
  • 提供方完成发出数据项。在这种情况下,数据流将关闭,调用 collect 的协程则继续执行。

五 数据流捕获异常

使用 catch 中间运算符

class LatestNewsViewModel(private val newsRepository: NewsRepository
) : ViewModel() {init {viewModelScope.launch {newsRepository.favoriteLatestNews// Intermediate catch operator. If an exception is thrown,// catch and update the UI.catch { exception -> notifyError(exception) }.collect { favoriteNews ->// Update View with the latest favorite news}}}
}

六 在不同 CoroutineContext 中执行

flow 构建器的提供方会通过从中收集的协程的 CoroutineContext 执行,并且如前所述,它无法从不同 CoroutineContext 对值执行 emit 操作。如需更改数据流的 CoroutineContext,使用中间运算符 flowOn

class NewsRepository(private val newsRemoteDataSource: NewsRemoteDataSource,private val userData: UserData,private val defaultDispatcher: CoroutineDispatcher
) {val favoriteLatestNews: Flow<List<ArticleHeadline>> =newsRemoteDataSource.latestNews.map { news -> // Executes on the default dispatchernews.filter { userData.isFavoriteTopic(it) }}.onEach { news -> // Executes on the default dispatchersaveInCache(news)}// flowOn affects the upstream flow ↑.flowOn(defaultDispatcher)// the downstream flow ↓ is not affected.catch { exception -> // Executes in the consumer's contextemit(lastCachedNews())}
}

七 Jetpack 库中的数据流

Flow with Room 接收有关数据库更改的通知

@Dao
abstract class ExampleDao {@Query("SELECT * FROM Example")abstract fun getExamples(): Flow<List<Example>>
}

八 将基于回调的 API 转换为数据流

callbackFlow 是一个数据流构建器,允许您将基于回调的 API 转换为数据流。

class FirestoreUserEventsDataSource(private val firestore: FirebaseFirestore
) {// Method to get user events from the Firestore databasefun getUserEvents(): Flow<UserEvents> = callbackFlow {// Reference to use in Firestorevar eventsCollection: CollectionReference? = nulltry {eventsCollection = FirebaseFirestore.getInstance().collection("collection").document("app")} catch (e: Throwable) {// If Firebase cannot be initialized, close the stream of data// flow consumers will stop collecting and the coroutine will resumeclose(e)}// Registers callback to firestore, which will be called on new eventsval subscription = eventsCollection?.addSnapshotListener { snapshot, _ ->if (snapshot == null) { return@addSnapshotListener }// Sends events to the flow! Consumers will get the new eventstry {offer(snapshot.getEvents())} catch (e: Throwable) {// Event couldn't be sent to the flow}}// The callback inside awaitClose will be executed when the flow is// either closed or cancelled.// In this case, remove the callback from FirestoreawaitClose { subscription?.remove() }}
}
http://www.yayakq.cn/news/521827/

相关文章:

  • 合肥网站建设套餐北京市网站公司网站
  • 自己想做个网站怎么做的自己做购物网站怎么做
  • 如何制定网站icon图标房产类网站建设
  • 做网站需要哪些步骤建设旅游网站
  • 专业的外贸网站建设免费网站后台管理系统模板
  • 网站备案修改域名ip京东联盟
  • 网站被很多公司抄袭济南阿里科技网站建设有限公司
  • dw 如何做自适应网站江苏建设网官方网站
  • 广州私人做网站河南省建设培训中心网站
  • 网站建设怎么收费网站关键词 html
  • 网站建设淮安国内永久免费域名申请网站
  • 山东住房城乡建设部网站公司装修流程
  • 做网站回答wordpress默认模版在哪
  • 无锡建设网站的公司哪家好杭州模板建站哪家好
  • 代做原创毕业设计网站光谷企业网站建设
  • 中国建设企业协会网站首页网站建设布局样式
  • 广西网站建设代理加盟女的做公关到底是干嘛的
  • html企业网站实例商务贸易网站建设
  • 新乡市做网站找哪个公司做汽车网站
  • 网站优化方案范文wordpress 登录后页面空白页
  • 网站开发公司飞沐西宁做网站君博解决
  • 番禺人才网站29网站建设全部
  • 网站前端代码有哪些问题大学网站模板html
  • 淘客请人做网站网站发送邮件连接怎么做
  • 本地做网站免费申请论坛网站
  • 淄博网站建设公司三农云南省省建设厅网站
  • 网站是先制作后上线么定制开发小程序报价
  • 做个营销型网站选网站建设公司有什么注意的
  • 个人做网站要注意什么条件龙岩网站建设哪里比较好
  • 南阳网站制作价格优惠活动推广文案