androidkotlinevent-busgreenrobot-eventbus-3.0

Using EventBus to finish an Activity from Base Activity?


Working on an existing project, I found this rather uncommon piece of implementation (to me at least). Since I am not in contact with the previous developer who already left, and before I dismiss this as a case of simply copy and pasting code from another part of our codebase, I would like to ask the SO community about this.

Here's your everyday activity that extends BaseActivity, and the implementation:

class SomeActivity : BaseActivity(R.layout.some_activity) {
    ...
    private fun close() {
        if(backToMain)
            finish()
        } 
        else
            goToMain(this)
    }

    companion object {
        fun goToMain(activity: AppCompatActivity) {
            val intent = Intent(activity, MainActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
            activity.startActivity(intent)
            EventBus.getDefault().post(Event(Event.Type.ActivityFinish))
        }
    }
    ...
}

In BaseActivity.kt, there's a subscription to the event which calls finish().

@Subscribe override fun onEvent(event: Event) {
    when (event.type) {
        Event.Type.ActivityFinish -> super.finish()
        else -> {}
    }
}

Now, why would anyone use EventBus to call Activity.finish() from the extended BaseActivity, instead of just calling it then and there (in the above SignActivity)? Even if SomeActivity were actually a fragment, you could simply call getActivity.finish().

*With regards to the intent flags, you could also use Activity.finishAffinity() to finish all activities in the back stack if your min SDK is 16.

Thanks in advance for feeding my curiosity. :D


Solution

  • So, here's the deal with this. After some staring on the screen a couple of times and working more with the codebase, I found that the previous developer actually used the goToMain function from other activities (do people really do this? O_o). Nonetheless, since the "Activity" object is still passed, there is no reason that I could think of for using an EventBus in this particular scenario (because you can just call activity.finish()).

    In conclusion, the developer probably just adapted this chunk of code from a different part of the app, thinking this is how it works.


    What is EventBus?

    EventBus is an Android optimized event bus that simplifies communication between Activities, Fragments, Threads, Services, etc.

    i.e. Not running a static method to call an activity's own extended functions.