Wednesday, 11 September 2024

Simple Example of Sealed class using ViewModel

 1.  MyViewModel

MyViewModel

class MyViewModel : ViewModel() {
private val _state = MutableStateFlow<StateController>(StateController.Empty)
val state: StateFlow<StateController>
get() = _state

fun login(name: String, pass: String) {
_state.value = StateController.Loading
viewModelScope.launch {
delay(2000)

if (name == "simi" && pass == "123") {
_state.value = StateController.Success("Authenticated")
} else {
_state.value = StateController.Error("Invalid UserID & Password")
}
}
}
}
2. StateController
StateController
package com.example.sealedviewmodelex

sealed class StateController {
data object Loading : StateController()
data object Empty : StateController()
data class Success(val data: String) : StateController()
data class Error(val msg: String) : StateController()

}
3. MainActivity
MAinActivity
class MainActivity : AppCompatActivity() {
lateinit var viewModel: MyViewModel
lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
viewModel = ViewModelProvider(this)[MyViewModel::class.java]
binding.clickMe.setOnClickListener {
viewModel.login(binding.username.text
.toString(), binding.password.text.toString())
}
lifecycle.coroutineScope.launchWhenCreated {
viewModel.state.collect {
when (it) {
is StateController.Error -> {
binding.progress.visibility=View.GONE
Snackbar.make(binding.root, it.msg, Snackbar.LENGTH_SHORT).show()
}

is StateController.Loading -> {
binding.progress.visibility = View.VISIBLE
}

is StateController.Success -> {
binding.progress.visibility=View.GONE
Snackbar.make(binding.root, "Authenticated", Snackbar.LENGTH_SHORT).show()
}

StateController.Empty -> {

}
}
}
}
}
}

4. Dependencies
libs class:
lifecycle_version = "2.8.4"
androidx-lifecycle-viewmodel-ktx = { group = "androidx.lifecycle", 
name = "lifecycle-viewmodel-ktx", version.ref = "lifecycle_version" }
buildFeatures{
dataBinding=true
}
implementation(libs.androidx.lifecycle.viewmodel.ktx)

No comments:

Post a Comment