kotlin 编写一个简单的天气预报app(三)broadcast换成eventbus

使用eventbus替换broadcast

将从Broadcast切换到EventBus有以下几个好处:

  • 解耦性:通过使用EventBus,您可以实现组件之间的解耦。传统的Broadcast机制需要发送方和接收方明确知道对方的存在,并且需要在代码中设置Intent过滤器和广播接收器。而EventBus使用了发布-订阅模式,发送方和接收方之间没有直接的依赖关系,它们只需要通过事件进行通信。这样可以减少组件之间的耦合性,提高代码的可维护性和灵活性。

  • 简化代码:使用Broadcast机制,您需要创建Intent对象,设置action、category和extras等信息,并通过发送Broadcast的方式来传递数据。而使用EventBus,您只需要定义一个事件类,然后通过发送事件来传递数据。这样可以减少繁琐的Intent操作和广播发送的代码。

  • 灵活性:EventBus提供了更灵活的事件传递方式。您可以根据需要定义不同的事件类型,并只订阅您感兴趣的事件。而Broadcast机制则需要通过Intent过滤器来筛选接收的广播内容。EventBus还支持不同的线程模式,您可以在接收事件时指定在哪个线程上进行处理,以避免阻塞主线程。

  • 性能优化:相比Broadcast机制,EventBus可以更好地管理事件的传递。EventBus使用了事件订阅者的注册和注销机制,它能够在适当的时候自动注册和注销订阅者,避免了不必要的事件接收和处理。此外,EventBus还使用了事件线程的处理方式,可以更好地控制事件的处理顺序和并发性。

总的来说,使用EventBus可以提供更好的代码解耦性、简化代码、提高灵活性和性能优化等好处。但也要根据实际情况来决定是否需要使用EventBus来替代Broadcast机制。

1. 删除原来broadcast的代码

2. 添加EventBus依赖

首先,在您的项目中添加EventBus库的依赖项。您可以通过在项目的 build.gradle 文件中的 dependencies 部分添加以下代码来实现此操作:

    implementation 'org.greenrobot:eventbus:3.2.0'

3. 定义事件类

创建一个用于传递的事件类。这是一个普通的 Kotlin 类,可以包含需要传递的数据或其他信息。例如:

class WeatherResponseEvent(val weatherResponse: WeatherResponse)

4. 注册订阅者:

在希望接收事件的地方,您需要注册一个订阅者来接收事件。这可以是 Activity,Fragment,或是其他任何类。通常,在类的 onCreate 或 onStart 方法中执行注册操作。例如:

class MainActivity : AppCompatActivity() {
    
    

    override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        EventBus.getDefault().register(this)
        findViewById<Button>(R.id.buttonSearch).setOnClickListener {
    
     searchCityNameWeather() }
    }

    override fun onDestroy() {
    
    
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
    //...
}

5. 声明事件处理方法

在订阅者类中,您可以定义一个方法来处理事件。该方法必须用 @Subscribe 注解进行标记,并且必须是公共方法。例如:

class MainActivity : AppCompatActivity() {
    
    
	    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(event: WeatherResponseEvent) {
    
    
        val weatherResponse = event.weatherResponse
        val kelvins = 273.15
        val cityName = weatherResponse.name
        val temperature = weatherResponse.main?.temp?.minus(kelvins)
        val maxTemperature = weatherResponse.main?.temp_max?.minus(kelvins)
        val minTemperature = weatherResponse.main?.temp_min?.minus(kelvins)
        val decimalFormat = DecimalFormat("#.#")
        val weatherStringArray = arrayListOf<String>()
        for(weather in weatherResponse.weather) {
    
    
            weatherStringArray += "main:${
      
      weather.main},description:${
      
      weather.description}"
        }

        @SuppressLint("SetTextI18n")
        findViewById<TextView>(R.id.weatherResult).text = "cityName:$cityName\n" +
                    "temperature:${
      
      decimalFormat.format(temperature)}\n" +
                "maxTemperature:${
      
      decimalFormat.format(maxTemperature)}\n" +
                "minTemperature:${
      
      decimalFormat.format(minTemperature)}\n" +
                "weather:$weatherStringArray"
    }
}

6. 发布事件

在发送事件的地方,您可以使用 EventBus.getDefault().post() 方法发布事件。例如:

object RetrofitClient {
    
    
//...
    private fun handleWeatherData(weatherData: WeatherResponse?) {
    
    
        if (weatherData != null) {
    
    
            val weatherResponseEvent = WeatherResponseEvent(weatherData)
            EventBus.getDefault().post(weatherResponseEvent)

            printWeatherData(weatherData)
        }
    }
//...

7.结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/ch122633/article/details/131976753