I try to figure out how to in best way finish an Activity from ViewModel. I found the one way to do this using LiveData object and emitting "signal".
I have a doubt that this solution has a overhead. So is it right solution or I should use more accurate?
So go to example: let's suppose that in an app is an activity MainActivity and view model like below:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val model = ViewModelProviders.of(this).get(MainViewModel::class.java)
model.shouldCloseLiveData.observe(this, Observer { finish() })
}
}
and as a companion to the MainActivity is a MainViewModel like below:
class MainViewModel(app: Application) : AndroidViewModel(app) {
val shouldCloseLiveData = MutableLiveData<Void>()
fun someAction(){
shouldCloseLiveData.postValue(null)
}
}