Call another function or variable inside a companion object android kotlin from main thread

862 Views Asked by At

Please help call another function outside the companion in Kotlin android main activity

class MainActivity{
    val name = "stackoverflow"

    companion object(){
        //call the both the name and showDialog from this main thread
    }
    
    fun showDialog(){
        Dialog.show()
    }
}
1

There are 1 best solutions below

2
Balwinder SIngh On

I assume you want to showDialog in MainActivity. let's say other fragments or maybe from MainActivity itself.

Best approaches from this :

  1. Share viewModel and have livData that lets the observer in MainActivity know to launch Dialog.
  2. Call (requireActivity as? MainActivity).showDialog() from fragment hosted in MainActivity.