Skip to content

Instantly share code, notes, and snippets.

@MrNtlu
Created December 28, 2022 14:12
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/d1add6f9111c2137d69ee12f9ae410ee to your computer and use it in GitHub Desktop.
Save MrNtlu/d1add6f9111c2137d69ee12f9ae410ee to your computer and use it in GitHub Desktop.
Token Auth Login Fragment
@AndroidEntryPoint
class LoginFragment : Fragment() {
private val viewModel: AuthViewModel by viewModels()
private val tokenViewModel: TokenViewModel by activityViewModels()
private lateinit var navController: NavController
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_login, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
navController = Navigation.findNavController(view)
val loginTV = view.findViewById<TextView>(R.id.loginTV)
tokenViewModel.token.observe(viewLifecycleOwner) { token ->
if (token != null)
navController.navigate(R.id.action_loginFragment_to_main_nav_graph)
}
viewModel.loginResponse.observe(viewLifecycleOwner) {
when(it) {
is ApiResponse.Failure -> loginTV.text = it.errorMessage
ApiResponse.Loading -> loginTV.text = "Loading"
is ApiResponse.Success -> {
tokenViewModel.saveToken(it.data.token)
}
}
}
view.findViewById<Button>(R.id.loginButton).setOnClickListener {
viewModel.login(
Auth("test@gmail.com", "123Test"),
object: CoroutinesErrorHandler {
override fun onError(message: String) {
loginTV.text = "Error! $message"
}
}
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment