EventBus is a library of Greenbot . This is very simple for all users how to implement and its basic use. Here I will also share examples for better understanding. What is EventBus? EventBus is subscribed/publish event bus to communication between components with limited lines of code, in short, its bus for events transfers the data between one activity(class) to another to reflect the changes based on our needs. That makes the data exchange between components like Activity, Fragment, Services, and any kind of backgrounds threads pretty easy. EventBus can handle the threading for us: events can be posted in threads different from the posting thread. Common use can be dealing with UI changes. In Android, UI changes must be done in the Main(UI) thread. In other words, networking or more time-consuming task cannot be handled in the Main thread, for that we must use AsyncTask or Handler to make it more smooth. Now we have one more options use EventBus to change the UI po...
EventBus is a library of Greenbot. This is very simple for all users how to implement and its basic use. Here I will also share examples for better understanding.
What is EventBus?
EventBus is subscribed/publish event bus to communication between components with limited lines of code, in short, its bus for events transfers the data between one activity(class) to another to reflect the changes based on our needs.
That makes the data exchange between components like Activity, Fragment, Services, and any kind of backgrounds threads pretty easy.
EventBus can handle the threading for us: events can be posted in threads different from the posting thread.
Common use can be dealing with UI changes. In Android, UI changes must be done in the Main(UI) thread. In other words, networking or more time-consuming task cannot be handled in the Main thread, for that we must use AsyncTask or Handler to make it more smooth. Now we have one more options use EventBus to change the UI portion as per our needs. Let us understand step by step with a simple example. You guys can make it more complex as per your requirement.
Usage and simple code
EventBus Publish-Subscribe |
An Event Bus can also massively reduce boilerplate code: No need for interfaces, callbacks for asynchronous communication, or data propagation through all software layers. It keeps your software architecture decoupled and flexible.
You need the following four parts to send and receive messages through your EventBus:
- The bus
- The event
- The sender
- The subscriber
The Bus
We only need to use one EventBus object throughout the application. Just call EventBus.getDefault() to receive default object.
EventBus mEventBus = EventBus.getDefault();
The EventEvents are just POJO (Plain Old Java Object) without any specific implementation:
public class MessageEvent { private String message; public
MessageEvent
(String message) { this.message = message; } public String getMessage() { return message; } }
An Event is just an object that is posted from the sender on the bus and will be delivered to any receiver class were subscribing to the same event type.
The Sender
You can post any event from any part of your whole Android application. Just get the default EventBus instance by calling EventBus.getDefault() and submit any event by calling post():
EventBus.getDefault().post(new MessageEvent("Hello EventBus!”);
The Subscriber
We have a bus, an event, and already a sender. Most of the things we have. What is missing now? Right, someone should listen to our MessagEvent. We can declare as many subscribers as we want and we are not limited to specific Android classes. Theoretically, every Java class can act as a subscriber.
Lets we go with a simple example.
1. Define dependency in build.gradle in the main module
compile 'org.greenrobot:eventbus:3.0.0'
2. AndroidManifest.xml: Define Activity, Broadcast Receiver.
<manifest>
<uses-permission android:name="android.permission.INTERNET">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE">
<application>
<!-- ... -->
<receiver android:name="com.prashant.adesara.broadcast.NetworkStateReceiver">
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED">
<action android:name="android.net.wifi.STATE_CHANGE">
</action></action></intent-filter>
</receiver>
</application>
</uses-permission></uses-permission></manifest>
3. MainActivity: Subscribe/publish the EventBus over here.
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register to the event bus EventBus.getDefault().register(this); }
@Subscribe
public void onMessageEvent(
NetworkStateChanged networkStateChanged){ if(networkStateChanged.isInternetConnected()) { System.out.println("Network is connected"); // You can change UI Part based on requirement
(
} else { System.out.println("Network is not connected");
// You can change UI Part based on requirement(Lost Connection Image)
} } @Override protected void
onDestroy() { super.
onDestroy(); EventBus.getDefault().unregister(this); } }
4. NetworkStateChanged: Create POJO/Model for NetworkStateChanged.
public class NetworkStateChanged { private boolean mIsInternetConnected; public NetworkStateChanged(boolean isInternetConnected) { mIsInternetConnected = isInternetConnected; } public boolean isInternetConnected() { return mIsInternetConnected; } }
5. NetworkStateReceiver: Receives when net-connected or disconnected.
public class NetworkStateReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // Send network state changed NetworkInfo networkInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected()) { // Internet connection available EventBus.getDefault().post(new NetworkStateChanged(true)); } else { // Lost Internet connection EventBus.getDefault().post(new NetworkStateChanged(false)); } } }
Of course, a subscriber can also listen to multiple events at the same time. The following snippet shows the necessary code to prepare a Fragment to listen to two different types of events:
@Override public void onResume() { super.onResume(); EventBus.getDefault().register(this); } @Override public void onPause() { EventBus.getDefault().unregister(this); super.onPause(); } // This method will be called when a MessageEvent is posted
@Subscribe
public void onEvent(MessageEvent event){ Toast.makeText(getActivity(), event.getMessage(), Toast.LENGTH_SHORT).show(); } // This method will be called when a AnotherEvent is posted
@Subscribe
public void onEvent(AnotherEvent event){ processEvent(event); }
If you are satisfied with this post then please give your comments.
Thanks for your interest!!!
Cunda
ReplyDeleteMordoğan
Alibeyli
Tahtakale
Akköprü
EOZ
Adana
ReplyDeleteElazığ
Kayseri
Şırnak
Antep
RDLT
ankara parça eşya taşıma
ReplyDeletetakipçi satın al
antalya rent a car
antalya rent a car
ankara parça eşya taşıma
JLJRLL
Tokat Lojistik
ReplyDeleteKonya Lojistik
Mersin Lojistik
Karabük Lojistik
Samsun Lojistik
1AA
ordu evden eve nakliyat
ReplyDeletebursa evden eve nakliyat
konya evden eve nakliyat
osmaniye evden eve nakliyat
bitlis evden eve nakliyat
PRCQ5S
116E0
ReplyDeleteBolu Parça Eşya Taşıma
Samsun Şehir İçi Nakliyat
Bitci Güvenilir mi
Ardahan Evden Eve Nakliyat
Altındağ Boya Ustası
Ünye Parke Ustası
Kırşehir Lojistik
Kripto Para Nedir
Karaman Parça Eşya Taşıma
0BB8C
ReplyDeleteşırnak sohbet sitesi
sesli sohbet odası
sinop sesli sohbet uygulamaları
bilecik sesli sohbet sesli chat
bayburt canlı görüntülü sohbet siteleri
mobil sohbet sitesi
eskişehir kızlarla rastgele sohbet
sesli sohbet sitesi
rize mobil sohbet
D1494
ReplyDeleteBaby Doge Coin Hangi Borsada
Coin Para Kazanma
Clysterum Coin Hangi Borsada
Sohbet
Twitter Beğeni Hilesi
Tumblr Takipçi Hilesi
Cate Coin Hangi Borsada
Kripto Para Oynama
Bitcoin Hesap Açma
CF7E4
ReplyDeleteKwai Takipçi Satın Al
Sohbet
Bitcoin Nasıl Alınır
Btcturk Borsası Güvenilir mi
Kripto Para Çıkarma Siteleri
Bitcoin Çıkarma Siteleri
Kripto Para Kazma Siteleri
Binance Kaldıraçlı İşlem Nasıl Yapılır
Spotify Dinlenme Satın Al
6A5DD
ReplyDeletedexview
trezor suite
avalaunch
spookyswap
DefiLlama
uniswap
bscpad
eigenlayer
zkswap
A9118B525C
ReplyDeletedüşmeyen takipçi satın al
D88CA80F1E
ReplyDeletetiktok takipçi