Created
December 28, 2022 14:18
-
-
Save MrNtlu/8b0df6374a735430e2c31f35cbc8facf to your computer and use it in GitHub Desktop.
Token Auth Main Fragment
This file contains 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 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