Hi some help needed please. I have one Activity bu...
# android
l
Hi some help needed please. I have one Activity but to keep it tidy I outsourced some of the code to another class called
EventHandler
. Im working with Kotlin + Dagger 2 (not dagger-android) with currently one simple
Component
which is built in application class.
EventHandler
needs the activity or at least some views and I will inject it into my activity so its a circular dependency. Is there a better way to do this or to avoid the circular dependency?
r
If I were you, I would try to remove the activity/view dependency from the
EventHandler
l
@rook Its difficult to avoid because I will start fragments there:
Copy code
activity.fragment_navhost.findNavController().navigate(destinationId)
As you can see, I need either the activity or the view. I also handling other events here.
r
You can expose that in an interface to the activity and then just pass the
destinationId
that way
l
sorry can you elaborate your thoughts a bit?
@rook Actually the
EventHandler
class implements an
NavigationEvent
interface and some other events
@rook ok I guess I know what you mean but that will mess up my activity. Thats the reason why I want to outsource the code
r
I can’t see your code, so I can’t say specifically how to change it to go the direction I’m talking about, but I basically would do something like:
Copy code
interface NavigableView { fun navigate(navigationKey: String) }
interface MyView : NavigableView

class EventHandler() {
  var currentView: NavigableView? = null

  fun navigate(key: String) { currentView.navigate(key) }
}

class MyActivity() : Activity, MyView {
  override fun navigate(navigationKey: String){
    //navigate somewhere
  }
}
l
@rook Its still a circular dependency when I have to set
currentView
in my activity like:
Copy code
mEventHandler.currentView = this
My Code looks currently like this:
Copy code
class MainActivity : BaseActivity(), NavigationEvent {
    override fun startFragment(destinationId: Int) {
        this.fragment_navhost.findNavController().navigate(destinationId)
    }
And I just want to move the
NavigationEvent
implementation to the
EventHandler
r
If you expose it via interface and don’t inject the view, you break the circular dependency
l
@rook how can I do that?
r
provide the
EventHandler
to every view, and at the entry point of every view, have it set the
currentView
on the
EventHandler
to itself
Copy code
override fun onStart() {
  eventHandler.currentView = this
}
l
@rook but I don't own the view, its in my case
fragment_navhost
@rook I have a more complete implementation in Java. Are you more familiar with Java or Kotlin?
r
I’m plenty comfortable with either
l
ok cool. I will give you an example of my code