Android Kotlin SharedFlow

2023-11-01

SharedFlow 会从其中收集值得所有使用方法中发出数据

简而言之就是 像普通的流只可以一方发送。一方接受

而这个流可以一方发送。多方接受

下面上代码演示

SharedFlowFragment
package com.example.android_flow_practice.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.example.android_flow_practice.databinding.FragmentSharedFlowBinding
import com.example.android_flow_practice.viewmodel.SharedFlowViewModel


class SharedFlowFragment : Fragment() {
    private val TAG = "ArticleFragment"
    private val viewModel: SharedFlowViewModel by viewModels()

    private val mBinding: FragmentSharedFlowBinding by lazy {
        FragmentSharedFlowBinding.inflate(layoutInflater)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return mBinding.root
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        mBinding.btnStart.setOnClickListener {
            viewModel.startRefresh()
        }
        mBinding.btnStop.setOnClickListener {
            viewModel.stopRefresh()
        }
    }
}

布局

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragment.TextFragment">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <fragment
            android:id="@+id/fragment_1"
            android:name="com.example.android_flow_practice.fragment.TextFragment"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />

        <fragment
            android:id="@+id/fragment_2"
            android:name="com.example.android_flow_practice.fragment.TextFragment"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />

        <fragment
            android:id="@+id/fragment_3"
            android:name="com.example.android_flow_practice.fragment.TextFragment"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />

    </LinearLayout>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/btn_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|start"
        android:layout_marginStart="8dp"
        android:layout_marginBottom="8dp"
        android:src="@android:drawable/ic_media_play"


        />


    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/btn_stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_marginStart="8dp"
        android:layout_marginBottom="8dp"
        android:src="@android:drawable/ic_notification_overlay"

        />



</FrameLayout>
TextFragment
package com.example.android_flow_practice.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.example.android_flow_practice.R
import com.example.android_flow_practice.common.LocalEventBus
import com.example.android_flow_practice.databinding.FragmentSharedFlowBinding
import com.example.android_flow_practice.databinding.FragmentTextBinding
import com.example.android_flow_practice.viewmodel.ArticleViewModel
import kotlinx.coroutines.flow.collect


class TextFragment : Fragment() {

    private val mBinding: FragmentTextBinding by lazy {
        FragmentTextBinding.inflate(layoutInflater)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return mBinding.root
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        lifecycleScope.launchWhenCreated {
            LocalEventBus.events.collect {
                mBinding.tvText.text = it.timestamp.toString()
            }
        }

    }
}

布局

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragment.TextFragment">

    <TextView
        android:layout_gravity="center"
        android:id="@+id/tv_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</FrameLayout>

核心代码

package com.example.android_flow_practice.common

import kotlinx.coroutines.flow.MutableSharedFlow

object LocalEventBus {
    val events = MutableSharedFlow<Event>()

    suspend fun postEvent(event: Event) {
        events.emit(event)
    }
}

data class Event(val timestamp: Long)
package com.example.android_flow_practice.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.android_flow_practice.common.Event
import com.example.android_flow_practice.common.LocalEventBus
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

class SharedFlowViewModel : ViewModel() {
    private lateinit var job: Job

    fun startRefresh() {
        job = viewModelScope.launch(Dispatchers.IO) {
            while (true) {
                LocalEventBus.postEvent(Event(System.currentTimeMillis()))
            }

        }
    }

    fun stopRefresh() {
        if(::job.isInitialized){
            job.cancel()

        }
    }
}

点击启动三个fragment同事开始打印当前时间

点击停止 就停止打印 非常的好用

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android Kotlin SharedFlow 的相关文章

  • 如何重试已消耗的 Observable?

    我正在尝试重新执行失败的已定义可观察对象 一起使用 Retrofit2 和 RxJava2 我想在单击按钮时重试特定请求及其订阅和行为 那可能吗 service excecuteLoginService url tokenModel Ret
  • Android Activity 生命周期函数基础知识

    我正在测试这段代码 它显示活动所处的状态 public class Activity101Activity extends Activity String tag Lifecycle Called when the activity is
  • Adobe 是否为其 PDF 阅读器提供 Android SDK 或 API? [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 我希望能够在我们的应用程序内的视图中显示本地 PDF 文件 在 Android 4 03 下的平板电脑上运行 目前 我们将 Adob eR
  • 找不到处理意图 com.instagram.share.ADD_TO_STORY 的活动

    在我们的 React Native 应用程序中 我们试图让用户根据视图 组件中的选择直接将特定图像共享到提要或故事 当我们尝试直接使用 com instagram share ADD TO FEED 进行共享时 它以一致的方式完美运行 但是
  • Android 中 Kotlin 协程的正确使用方式

    我正在尝试使用异步更新适配器内的列表 我可以看到有太多的样板 这是使用 Kotlin 协程的正确方法吗 这个可以进一步优化吗 fun loadListOfMediaInAsync async CommonPool try Long runn
  • 无法访问 com.google.android.gms.internal.zzbfm 的 zzbfm 类文件未找到

    我正在将我的 Android 应用程序项目从GCM to FCM 为此 我使用 Android Studio 中的 Firebase 助手工具 并遵循 Google 开发人员指南中的说明 一切都很顺利 并将我的应用程序代码更改为FCM根据助
  • 获取当前 android.intent.category.LAUNCHER 活动的实例

    我创建了一个库项目 并在多个应用程序之间共享 我实现了一个简单的会话过期功能 该功能将在一段时间后将用户踢回到登录屏幕 登录屏幕活动是我的主要活动 因此在清单中它看起来像这样
  • 如何在PreferenceActivity中添加工具栏

    我已经使用首选项创建了应用程序设置 但我注意到 我的 PreferenceActivity 中没有工具栏 如何将工具栏添加到我的 PreferenceActivity 中 My code 我的 pref xml
  • 如何使用InputConnectionWrapper?

    我有一个EditText 现在我想获取用户对此所做的所有更改EditText并在手动将它们插入之前使用它们EditText 我不希望用户直接更改中的文本EditText 这只能由我的代码完成 例如通过使用replace or setText
  • 如何默认在 ActionOpenDocument 意图中显示“内部存储”选项

    我需要用户选择一个自定义文件类型的文件 并将其从 Windows 文件资源管理器拖到 Android 设备上 但默认情况下内部存储选项不可用 当我使用以下命令启动意图时 var libraryIntent new Intent Intent
  • 在 android DatePickerDialog 中将语言设置为法语

    有什么办法可以让日期显示在DatePickerDialog用法语 我已经搜索过这个但没有找到结果 这是我的代码 Calendar c Calendar getInstance picker new DatePickerDialog Paym
  • Android Studio - Windows 7 上的 Android SDK 问题

    我对 Google i o 2013 上发布的最新开发工具 Android Studio 有疑问 我已经成功安装了该程序并且能够正常启动 我可以导入现有项目并对其进行编辑 但是 当我尝试单击 SDK 管理器图标或 AVD 管理器图标时 或者
  • 我的设备突然没有显示在“Android 设备选择器”中

    我正在使用我的三星 Galaxy3 设备来测试过去两个月的应用程序 它运行良好 但从今天早上开始 当我将设备连接到系统时 它突然没有显示在 Android 设备选择器 窗口中 我检查过 USB 调试模式仅在我的设备中处于选中状态 谁能猜出问
  • .isProviderEnabled(LocationManager.NETWORK_PROVIDER) 在 Android 中始终为 true

    我不知道为什么 但我的变量isNetowrkEnabled总是返回 true 我的设备上是否启用互联网并不重要 这是我的GPSTracker class public class GPSTracker extends Service imp
  • Android 套接字和 asynctask

    我即将开始制作一个应该充当 tcp 聊天客户端的应用程序 我一直在阅读和阅读 我得出的结论是最好 如果不需要 将我的套接字和异步任务中的阅读器 问题是我不确定从哪里开始 因为我是 Android 新手 这至少对我来说是一项艰巨的任务 但据我
  • 如何在Xamarin中删除ViewTreeObserver?

    假设我需要获取并设置视图的高度 在 Android 中 众所周知 只有在绘制视图之后才能获取视图高度 如果您使用 Java 有很多答案 最著名的方法之一如下 取自这个答案 https stackoverflow com a 24035591
  • 实现滚动选择 ListView 中的项目

    我想使用 ListView 您可以在其中滚动列表来选择一个项目 它应该像一个 Seekbar 但拇指应该是固定的 并且您必须使用该栏来调整它 我面临的一个问题是 我不知道这种小部件是如何调用的 这使得我很难搜索 所以我制作了下面这张图片 以
  • android sdk 的位置尚未在 Windows 操作系统的首选项中设置

    在 Eclipse 上 我转到 windows gt Android SDK 和 AVD Manager 然后弹出此消息 Android sdk 的位置尚未在首选项中设置 进入首选项 在侧边栏找到 Android 然后会出现一个 SDK 位
  • 如何将 google+ 登录集成到我的 Android 应用程序中?

    大家好 实际上我需要通过我的应用程序从 google 登录人们 现在我阅读了 google 上的文档 其中指出 要允许用户登录 请将 Google Sign In 集成到您的应用中 初始化 GoogleApiClient 对象时 请求 PL
  • 节拍匹配算法

    我最近开始尝试创建一个移动应用程序 iOS Android 它将自动击败比赛 http en wikipedia org wiki Beatmatching http en wikipedia org wiki Beatmatching 两

随机推荐

  • JDBC数据库驱动的下载、安装与连接

    1 常用的数据库驱动下载 使用JDBC操作数据库 需要使用数据库厂商提供的驱动程序 通过驱动程序可以与数据库进行交互 1 1 常用的数据库厂商驱动下载地址 1 1 1 MySQL数据库 https dev mysql com downloa
  • Pytorch基于DDPM+InceptionNext+数据增强的图像分类(一)

    项目简介 本项目旨在通过使用深度学习技术实现对图像进行分类 我采用了DDPM Deep Dynamic Probabilistic Modeling 和InceptionNext两个模型的结合 以提高图像分类的准确性和性能 同时 我还使用了
  • 拷贝构造函数和赋值构造函数声明为私有的作用

    转载 http blog csdn net rabbit729 article details 4000500 每个类只有一个赋值函数 由于并非所有的对象都会使用拷贝构造函数和赋值函数 程序员可能对这两个函数有些轻视 请先记住以下的警告 在
  • dom-to-image 将vue中未显示的组件转成图片, 并上传

    目录 一 dom to image基本使用 二 注意点 三 生成的图片上传至服务器 1 base64 转 File 格式 2 blob 转 File 格式 3 在页面展示生成的图片 4 最终dom转图片函数 5 上传图片 6 问题未解决 四
  • word自带公式编辑

    快捷键 公式编辑 alt 上标 x i 空格 下标 x i 空格 实数R doubleR 空格 偏微分算子 partial 极限 limit 按空格后会显示一串很长的式子 再空格就变成了数学公式 积分 int 二重积分 iint 三重积分
  • python的smtplib发送带附件邮件

    usr bin python coding UTF 8 author import smtplib logging 加载smtplib模块 from email mime text import MIMEText from email ut
  • 如何使用chatGPT生成小红书种草文案

    如何使用chatGPT生成小红书种草文案 小红书拥有超千万的日活用户 为商家提供了广阔的变现空间和机会 成为商家选择在小红书上推广的原因之一 小红书种草文案 例如具有影响力的热门话题 产品使用方法等内容可以让消费者迅速了解产品为品牌带来更多
  • nginx转发后如何获取真实的ip地址

    前言 最近做一个团队的打卡系统 需要通过连接实验室WiFi来判是否人在实验室 网上千篇一律的获取主机ip的方法由于我使用了nginx反向代理 导致获取到的ip地址为127 0 0 1 这肯定是不符合我们验证标准的 还有就是失去了校验的意义了
  • 人工智能笔记

    第一章 绪论 1956年正式提出人工智能 artificial intelligence AI 这个术语并把它作为一门新兴科学的名称 20世纪三大科学技术成就 空间技术 原子能技术 人工智能 智能是知识与智力的总和 知识是一切智能行为的基础
  • Flutter 在MAC环境下jenkins+fastlane+gitlab实现自动打包部署(看这一篇就够了,小而精)

    实现办公局域网下的jenkins服务 Flutter配置 文档 jenkins安装 通过homebrew安装 1 安装homebrew bin bash c curl fsSL https raw githubusercontent com
  • 谷歌播客Google PodCasts解析脚本

    解析某个频道 全部的结果 import json import requests feed url https podcasts google com feed aHR0cHM6Ly93d3cueGltYWxheWEuY29tL2FsYnV
  • 我的LLVM学习笔记——OLLVM混淆研究之FLA篇

    因为要做代码保护 所以抽时间研究了下OLLVM中的三种保护方案 BCF Bogus Control Flow 中文名虚假控制流 FLA Control Flow Flattening 中文名控制流平坦化 SUB Instructions S
  • vue使用wangEditor

    vue版本2 0 editor5 1 23版本 editor for vue 1 0 2版本 api文档入口 效果图 点击查看如何封装 安装步骤入口 npm install wangeditor editor save npm instal
  • 多路选择器MUX总结-IC学习笔记(八)

    多路复用器是一种组合电路 它从许多输入信号中选择一个作为输出 本文先介绍两个MUX的简单应用 主要关于如何将verilog与物理实现对应 第二当MUX作为时钟切换电路时如何避免毛刺 glitch 文章目录 1 1 MUX code与物理实现
  • grafana配置MySQL持久化存储并配置HTTPS

    Grafana 配置 MySQL 数据持久化存储 一 mysql8 0 30 安装 1 1 解压并初始化 MySQL8 0 30 查询是否存在 MariaDB 和 MySQL 存在需要删除后进行安装 rpm qa grep MariaDB
  • 目标检测VOC标注格式中,将斜框标注转化为水平框

    目标检测VOC格式数据集obb标注向hbb标注的转换 polygon 2 bndbox polygon obb 和bndbox hbb 介绍 polygon obb bndbox hbb polygon2bndbox转换原理 polygon
  • unturned服务器修改空投频率,unturned 服务器设置

    unturned 服务器设置 内容精选 换一换 区块链服务状态为 弹性IP异常 排查项 弹性公网IP已 解绑 或被释放 在BCS控制台 服务管理页面中的目标服务卡片中 单击 更多 gt 更新访问地址 查看弹性公网IP 登录网络控制台 查找目
  • ajax success function(data)后的data数据无法使用Uncaught TypeError: Cannot read property ‘xxx‘ of undefined

    问题描述 前端小白 在不了解ajax机制的情况下误使用函数返回ajax中需要时间完成的ajax函数 导致return后的data无法在后面的script代码块中正常使用 function getData ajax type get url
  • procfs使用及字符设备

    以下内容由chatgpt给出 以下是一个使用procfs接口创建设备节点的示例代码 include
  • Android Kotlin SharedFlow

    SharedFlow 会从其中收集值得所有使用方法中发出数据 简而言之就是 像普通的流只可以一方发送 一方接受 而这个流可以一方发送 多方接受 下面上代码演示 SharedFlowFragment package com example a