Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Event/Data wrapper
- sealed class Event<out T> {
- class Loading<out T> : Event<T>()
- data class Success<out T>(val data: T) : Event<T>()
- data class Failure<out T>(val throwable: Throwable) : Event<T>()
- }
- // ViewModel
- class HomeViewModel : ViewModel() {
- val text: LiveData<Event<String>> = liveData {
- emit(Event.Loading())
- try {
- emit(Event.Success("This is home fragment"))
- } catch(exception: Exception) {
- emit(Event.Failure(exception))
- }
- }
- }
- // Fragment
- class HomeFragment : Fragment() {
- private lateinit var homeViewModel: HomeViewModel
- override fun onCreateView(
- inflater: LayoutInflater,
- container: ViewGroup?,
- savedInstanceState: Bundle?
- ): View? {
- homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java)
- val root = inflater.inflate(R.layout.fragment_home, container, false)
- val textView: TextView = root.findViewById(R.id.text_home)
- homeViewModel.text.observe(viewLifecycleOwner, Observer {
- when (it) {
- is Event.Loading -> { /*show progress*/ }
- is Event.Success -> textView.text = it.data
- is Event.Failure -> { /*show progress, show error*/ }
- }
- })
- return root
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement