Created
July 8, 2020 09:31
-
-
Save rhonyabdullah/5ccb22ca5385bf67b344893dcc202345 to your computer and use it in GitHub Desktop.
Shared Android ViewModel between Activity and Fragment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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}") | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@AndroidEntryPoint | |
class MainActivity : AppCompatActivity() { | |
override fun onResume() { | |
super.onResume() | |
viewModel.testState++ | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//@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