Android : Kotlin Initialise interface variable and call its method

Viewed 32

I have a base activity which observes the change of network connectivity status.

    class BaseActivity : AppCompatActivity() {
    private val connectivityLiveStatus: ConnectionLiveStatus = ConnectionLiveStatus(this)

    init {
        observeConnectivity()
    }

    private fun observeConnectivity(){
        connectivityLiveStatus.observe(this , Observer {status ->
             handleConnectivityStatus()  
        })
    }
    private fun handleConnectivityStatus(){} 
}

I want my MainActivity to inherit this BaseActivity class and have its own definition of handling change in connectivity.

But since MainActivity already inherits AppCompatActivity()

class MainActivity : AppCompatActivity() {

lateinit var movieViewModel : MoviesViewModel
lateinit var moviesAdapter : MoviesAdapter
lateinit var movieRecyclerView: RecyclerView
lateinit var connectivityLiveStatus: ConnectionLiveStatus
private var pageAlreadyLoaded = false

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    init()

}

I cannot Inherit another Class since Kotlin does not allow multiple Inheritence.

So I created an Interface called BaseActivityListener.

interface BaseActivityListener {
    fun handleNetworkConnectivityChange(status : Boolean)
}

And inherited this interface in the MainActivity to have its own definition for handling Network Connectivity changes.

class MainActivity : AppCompatActivity() , BaseActivityListener {

lateinit var movieViewModel : MoviesViewModel
lateinit var moviesAdapter : MoviesAdapter
lateinit var movieRecyclerView: RecyclerView
lateinit var connectivityLiveStatus: ConnectionLiveStatus
private var pageAlreadyLoaded = false

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    init()

}

override fun handleNetworkConnectivityChange(status: Boolean) {
    TODO("handle network connectivity change")
}

But Since the Network Connectivity changing status is only available in the BaseActivity , I want to invoke the method handleNetworkConnectivityChange() of interface from the BaseActivity itself.

But I am Unable to create an object of this interface in BaseActivity using Kotlin, Which would have been done easily using the new operator in Java. enter image description here

How to initialise an interface Object in Kotlin ? I understand using interface makes it tight coupling , Is there any other way to do in this situation ?

0 Answers
Related