1. Pertama
compile 'com.squareup:otto:1.3.8'
2. Kedua create instance Bus di Application class
import android.app.Application; import android.util.Log; import com.squareup.otto.Bus; import com.squareup.otto.ThreadEnforcer; /** * Created by nostra on 3/15/16. */ public class OurApp extends Application{ private static Bus mEventBus; public static Bus getEventBus() { return mEventBus; } @Override public void onCreate() { super.onCreate(); mEventBus = new Bus(ThreadEnforcer.ANY); } }
3. Create pojo class untuk mendefinisikan Event. Pada kasus ini saya membuat event ketika user yg login sudah invalid.
/** * Created by nostra on 3/15/16. */ public class UnauthorizedEvent { public int status; public UnauthorizedEvent(int status) { this.status = status; } }
4. Publisher melakukan post event, berikut potongan logic-nya:
if(status==401){ OurApp.getEventBus().post(new UnauthorizedEvent(status)); return; }
5. Pada Activity Anda tambahkan register bus, seperti gambar dibawah:
@Override protected void onStart() { super.onStart(); OurApp.getEventBus().register(this); } @Override protected void onStop() { super.onStop(); OurApp.getEventBus().unregister(this); }
6. Langkah terakhir Activity melakukan subscribe, berikut contohnya:
@Subscribe public void unauthorizedEvent(UnauthorizedEvent event){ if(event.status==401){ Intent i = new Intent(this, Login.class); startActivity(i); finish(); } Log.i(TAG, "Event status :" + event.status); }
Yay, Mudah bukan. Untuk next level penggunaan Event bus kalian bisa baca artikel dibawah:
https://labs.ribot.co.uk/android-application-architecture-8b6e34acda65#.mimpcgc5v
Sekian dan terima kasih
No comments:
Post a Comment