Advertisement
Guest User

Untitled

a guest
Jan 27th, 2020
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.34 KB | None | 0 0
  1. // Event/Data wrapper
  2.  
  3. sealed class Event<out T> {
  4.     class Loading<out T> : Event<T>()
  5.     data class Success<out T>(val data: T) : Event<T>()
  6.     data class Failure<out T>(val throwable: Throwable) : Event<T>()
  7. }
  8.  
  9. // ViewModel
  10.  
  11. class HomeViewModel : ViewModel() {
  12.     val text: LiveData<Event<String>> = liveData {
  13.         emit(Event.Loading())
  14.         try {
  15.             emit(Event.Success("This is home fragment"))
  16.         } catch(exception: Exception) {
  17.             emit(Event.Failure(exception))
  18.         }
  19.     }
  20. }
  21.  
  22. // Fragment
  23.  
  24. class HomeFragment : Fragment() {
  25.  
  26.     private lateinit var homeViewModel: HomeViewModel
  27.  
  28.     override fun onCreateView(
  29.         inflater: LayoutInflater,
  30.         container: ViewGroup?,
  31.         savedInstanceState: Bundle?
  32.     ): View? {
  33.  
  34.         homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java)
  35.         val root = inflater.inflate(R.layout.fragment_home, container, false)
  36.         val textView: TextView = root.findViewById(R.id.text_home)
  37.  
  38.         homeViewModel.text.observe(viewLifecycleOwner, Observer {
  39.             when (it) {
  40.                 is Event.Loading -> { /*show progress*/ }
  41.                 is Event.Success -> textView.text = it.data
  42.                 is Event.Failure -> { /*show progress, show error*/ }
  43.             }
  44.         })
  45.  
  46.         return root
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement