Код: Выделить всё
TypeSafe< /code> - это герметичный класс, который имеет 3 класса подкапсов,
Loading()Код: Выделить всё
Success(data: T?)Код: Выделить всё
Error(message: String?)< /code> < /p>
Это живые данные для Boolean:
val mutableUserDataFound : MutableLiveData = MutableLiveData()< /code>
сейчас, используя это веселье: < /p>
fun availabilityCheckforUserInfo() = viewModelScope.launch {
mutableUserDataFound.postValue(TypeSafe.Loading())
try {
val userinfo = repository.getUserInfo()
if (userinfo != null) {
mutableUserDataFound.postValue(TypeSafe.Success(true))
} else {
mutableUserDataFound.postValue(TypeSafe.Success(false))
}
} catch (e: Exception) {
mutableUserDataFound.postValue(TypeSafe.Error(e.message))
}
}
< /code>
Я больше беспокоюсь о True и False, получение не нулевого пользователя Info не является моим первым приоритетом здесь,
у меня есть логика пользовательского интерфейса на основе этого.
, но
postValue(true or false)< /code>
even if the type is TypeSafe.Success()Further in UI I have when() expression inside observer
Edit:
MainActivity:
Код: Выделить всё
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
lateinit var mainViewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportActionBar?.hide()
viewModelInitializor()
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}
private fun viewModelInitializor() {
mainViewModel = ViewModelProvider(this,
MainViewModelProvider(
Repository(DBAccess(this))
)
).get(MainViewModel::class.java)
}
}
< /code>
fragmenta: < /p>
class FragmentA : Fragment(R.layout.fragment_a) {
private val TAG = "FragmentA"
private lateinit var binding: FragmentABinding
lateinit var mainViewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mainViewModel = (activity as MainActivity).mainViewModel
mainViewModel.availabilityCheckforUserInfo()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentABinding.bind(view)
mainViewModel.mutableUserDataFound.observe(viewLifecycleOwner, Observer { result ->
when (result) {
is TypeSafe.Loading -> {
// show progress bar animation
loadingAnimationConfig(View.VISIBLE)
}
is TypeSafe.Success -> {
Log.d(TAG, "success result = ${result.data}") // D success result = null
result.data?.let {
if (it) { // if available
Log.d(TAG, "if true $it")
// stop progess bar
mainViewModel.login()
loadingAnimationConfig(View.GONE)
} else { // if not available
Log.d(TAG, "else $it")
loadingAnimationConfig(View.GONE)
findNavController().navigate(R.id.inputFragment)
}
}
}
is TypeSafe.Error -> {
showToast(
msg = "Error: ${result.message}",
dursn = Toast.LENGTH_LONG
)
}
}
})
}
}
< /code>
result.data?.let {< /code> это добавляется временно, предотвращайте сбой пользовательского интерфейса.
Log.d(TAG, "success result = ${result.data}")< /code>
// D success result = nullПодробнее здесь: https://stackoverflow.com/questions/797 ... n-livedata