DEV Community

Cover image for เข้าใจเรื่อง EventBus ใน 3 นาที
Monthira Chayabanjonglerd for Ookbee

Posted on

4

เข้าใจเรื่อง EventBus ใน 3 นาที

รู้ว่าอ่านเองมันยาก เราเลยสรุปให้ อ่านเสร็จมาม่าสุกพอดี

ถ้าคุณอยากโยนค่าอะไรไปซะอย่าง โดยไม่ต้องรู้จักกัน ขอแค่ส่งไปแล้วได้รับก็พอ
ถ้าคุณอยากโยนค่าอะไรไปซะอย่าง โดยที่ไม่ต้องมานั่ง check ตลอดเวลาให้วุ่นวาย

EventBus เธอคือคำตอบ เพราะอะไรหล่ะ?

สมมุติเราส่งของให้ลูกค้า โดยมีตัวกลางอย่างพี่แมสเป็นคนส่ง ซึ่งตัวกลางอย่างพี่แมสก็ต้องมีระบบรับของจากเราและส่งของไปให้ลูกค้า ทำให้ลูกค้าตามพัสดุจากพี่แมสได้ และรู้ว่าของถึงแล้วเมื่อพี่แมสโทรมาบอก

image

จากในแผนภาพนี้มีการทำงานดังนี้

  1. ตกลงกันก่อนว่าจะส่งอะไร เช่น event ชื่อพัสดุ
  2. จากนั้นคนส่งจะส่ง event โดยการ post
  3. พี่แมสหรือ EventBus รับ event ที่ว่า
  4. พี่แมสเอาไปส่งให้คนรับ
  5. คนรับจะได้รับ event ตอนที่ subscribe เรียบร้อยแล้ว

มาใช้งาน EventBus กันเถอะ

ก่อนอื่น ใส่ลงไปใน dependency เสียก่อน

implementation 'org.greenrobot:eventbus:3.1.1'
Enter fullscreen mode Exit fullscreen mode

อ้างอิงจาก https://github.com/greenrobot/EventBus

พออ่านๆพบว่าใน README.md อ่านแล้วจะงงๆเพราะไม่ได้บอกถึงขารับ ดังนั้นสรุปการใช้งานดังน้ี

กำหนด Event ที่จะรับ อาจจะสร้าง model class มาตัวนึง เช่น

class MessageEvent(val message: String)
Enter fullscreen mode Exit fullscreen mode

ฝั่งขาส่ง อยากจะส่งอะไรก็ใช้เจ้า post พร้อมแนบ event ไปด้วย เช่น

EventBus.getDefault().post(MessageEvent("ReceivedGoods"))
Enter fullscreen mode Exit fullscreen mode

ฝั่งขารับ เราต้อง register มันก่อน มักจะใส่กันที่ onCreate()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    EventBus.getDefault().register(this)
}
Enter fullscreen mode Exit fullscreen mode

และ unregister ด้วย มักจะใส่ที่ onDestroy()

override fun onDestroy() {
    super.onDestroy()
    EventBus.getDefault().unregister(this)
}
Enter fullscreen mode Exit fullscreen mode

จากนั้นฝั่งขารับสร้าง function เพื่อ Subscribe Event ที่เราจะรับ โดยการใส่เจ้า @Subscribe และตามด้วย threadMode

ข้อควรระวัง function ที่รับ Event นั้น ต้อง public เท่านั้น ไม่งั้นแอป crash เพราะมันหาไม่เจอจ้า

@Subscribe(threadMode = ThreadMode.MAIN)
fun onMessageEvent(event: MessageEvent) {
    ...
}
Enter fullscreen mode Exit fullscreen mode

ลองเอาไป run ดู พบว่าทำงานได้แล้ว เย้ๆๆๆๆ

อ่านเพิ่มเติม

How to get started with EventBus in 3 steps


Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️