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