Skip to content

Instantly share code, notes, and snippets.

@MrNtlu
Created December 28, 2022 14:18
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 MrNtlu/8b0df6374a735430e2c31f35cbc8facf to your computer and use it in GitHub Desktop.
Save MrNtlu/8b0df6374a735430e2c31f35cbc8facf to your computer and use it in GitHub Desktop.
Token Auth Main Fragment
@AndroidEntryPoint
class MainFragment : Fragment() {
private val viewModel: MainViewModel by viewModels()
private val tokenViewModel: TokenViewModel by activityViewModels()
private lateinit var navController: NavController
private var token: String? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
return inflater.inflate(R.layout.fragment_main, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
navController = Navigation.findNavController(view)
tokenViewModel.token.observe(viewLifecycleOwner) { token ->
this.token = token
if (token == null)
navController.navigate(R.id.action_global_loginFragment)
}
val mainTV = view.findViewById<TextView>(R.id.infoTV)
viewModel.userInfoResponse.observe(viewLifecycleOwner) {
mainTV.text = when(it) {
is ApiResponse.Failure -> "Code: ${it.code}, ${it.errorMessage}"
ApiResponse.Loading -> "Loading"
is ApiResponse.Success -> "ID: ${it.data.userInfo._id}\nMail: ${it.data.userInfo.email_address}\n\nToken: $token"
}
}
view.findViewById<Button>(R.id.infoButton).setOnClickListener {
viewModel.getUserInfo(object: CoroutinesErrorHandler {
override fun onError(message: String) {
mainTV.text = "Error! $message"
}
})
}
view.findViewById<Button>(R.id.logoutButton).setOnClickListener {
tokenViewModel.deleteToken()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment