EventBus 事件总线

概述

功能:通过解耦发布者和订阅者简化Android事件传递
EventBus可以代替 Android 传统的 Intent , Handler , Broadcast 或接口函数,在Fragment,Activity,Service线程之间传递数据,执行方法。
特点:代码简洁,是一种发布订阅设计模式(观察者设计模式)。

订阅者订阅事件时,需要使用 @Subscribe() 注解标注订阅方法。
当事件发布时, EventBus 会自动将事件分发给订阅了相应事件的方法,然后执行该方法。
因此,@Subscribe()标注的方法会在事件被发布时自动被调用。

使用步骤

  1. 导入依赖
    implementation("org.greenrobot;eventbus:3.3.1")

  2. 定义事件对应的类(只是一个普通类)
    class ChangeColorEvent(val color:Int) {}

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    sealed class AudioEvent

    //音频开始加载的事件
    class AudioLoadEvent(val music:Song):AudioEvent()

    //开始播放事件
    object AudioStartEvent:AudioEvent()

    //暂停事件
    object AudioPauseEvent:AudioEvent()

    //进度变化事件
    class AudioProgressChangeEvent(val progress:Float):AudioEvent()
  3. 发送事件
    EventBus.getDefault().post(ChangeColorEvent(Color.MAGENTA))

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    fun start(){
    player.start() //播放音乐
    initTimer() //更新进度
    //发送音乐开始播放的事件
    EventBus.getDefault().post(AudioStartEvent)
    }

    private fun initTimer(){
    timer = TimerUtils() //使用定时器 实现每隔0.2秒钟刷新一次进度给外部
    timer?.order(TimerUtils.Order.NONE)
    timer?.timeInterval(200)
    timer?.start()
    timer?.setCallback{ _,_->
    val progress = currentTime().toFloat() / totalTime()
    //发送音乐播放进度的事件
    EventBus.getDefault().post(AudioProgressChangeEvent(progress))
    }
    }
  4. 注册和取消注册
    注册: EventBus.getDefault().register(this)
    取消注册: EventBus.getDefault().unregister(this)

  5. 订阅事件(谁接受谁订阅)

  • 加注解 : @Subscribe(threadMode = ThreadMode .MAIN)
  • 参数必须是发送时对应的类型
    1
    2
    3
    4
    5
    6
    7
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLoadEvent(event: AudioLoadEvent){
    initLoadUI(event.music)
    mRotateAnimation.reset()
    mBinding.progressPlayView.showPause()
    mBinding.progressPlayView.changeProgress(0f)
    }
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2023-2025 Annie
  • Visitors: | Views:

嘿嘿 请我吃小蛋糕吧~

支付宝
微信