Skip to content

Instantly share code, notes, and snippets.

@rhonyabdullah
Created July 8, 2020 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rhonyabdullah/5ccb22ca5385bf67b344893dcc202345 to your computer and use it in GitHub Desktop.
Save rhonyabdullah/5ccb22ca5385bf67b344893dcc202345 to your computer and use it in GitHub Desktop.
Shared Android ViewModel between Activity and Fragment
@AndroidEntryPoint
class LoginFragment : Fragment() {
private val viewModel: LoginViewModel by viewModels()
private val mainViewModel: MainViewModel by activityViewModels()
override fun onResume() {
super.onResume()
Log.d(LoginFragment::class.java.simpleName, "${activityVM.testState}")
}
}
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
override fun onResume() {
super.onResume()
viewModel.testState++
}
}
//@ActivityRetainedScoped if want to survive on configuration changes
@ActivityScoped
class MainViewModel @ViewModelInject constructor() : ViewModel() {
var testState: Int = 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment