Advertisement
Guest User

Untitled

a guest
Oct 29th, 2020
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.87 KB | None | 0 0
  1. package com.example.myapplication.ui.main
  2.  
  3. import android.os.Bundle
  4. import android.util.Log
  5. import androidx.fragment.app.Fragment
  6. import android.view.LayoutInflater
  7. import android.view.View
  8. import android.view.ViewGroup
  9. import androidx.lifecycle.*
  10. import com.example.myapplication.R
  11. import kotlinx.coroutines.Job
  12. import kotlinx.coroutines.channels.Channel
  13. import kotlinx.coroutines.flow.*
  14. import kotlinx.coroutines.launch
  15.  
  16.  
  17. class MainViewModel: ViewModel() {
  18. private var counter = 0
  19.  
  20. private val _events = MutableSharedFlow<String>(replay = 1, extraBufferCapacity = 500)
  21. val events = _events.asSharedFlow()
  22.  
  23. fun createEvent(eventName: String) {
  24. viewModelScope.launch {
  25. if (eventName.equals("ON_DESTROY")) {
  26. for (i in 0..8) {
  27. val eventValue = eventName + counter++
  28. Log.d("TESTING", "View model - Emitting event: $eventValue")
  29. _events.emit(eventValue)
  30. }
  31. } else {
  32. val eventValue = eventName + counter++
  33. Log.d("TESTING", "View model - Emitting event: $eventValue")
  34. _events.emit(eventValue)
  35. }
  36. }
  37. }
  38. }
  39.  
  40. class MainFragment : Fragment() {
  41.  
  42. companion object {
  43. fun newInstance() = MainFragment()
  44. }
  45.  
  46. private lateinit var viewModel: MainViewModel
  47.  
  48. override fun onCreateView(
  49. inflater: LayoutInflater, container: ViewGroup?,
  50. savedInstanceState: Bundle?
  51. ): View {
  52. return inflater.inflate(R.layout.main_fragment, container, false)
  53. }
  54.  
  55. override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
  56. super.onViewCreated(view, savedInstanceState)
  57. viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
  58.  
  59. viewLifecycleOwner.lifecycle.addObserver(LifecycleEventObserver { _: LifecycleOwner, event: Lifecycle.Event ->
  60. viewModel.createEvent(event.name)
  61. })
  62.  
  63. viewLifecycleOwner.lifecycleScope.launch {
  64. viewModel.events
  65. .onStart {
  66. val state = lifecycle.currentState
  67. Log.d("TESTING", "Flow observer1 - Starting in state $state")
  68. }
  69. .onCompletion {
  70. val state = lifecycle.currentState
  71. Log.d("TESTING", "Flow observer1 - Completing in state $state")
  72. }
  73. .catch {
  74. val state = lifecycle.currentState
  75. Log.d("TESTING", "Flow observer1 - caught $it")
  76. }
  77. .collect {
  78. val state = lifecycle.currentState
  79. Log.d("TESTING", "Flow observer1 - Got value $it in state $state")
  80. }
  81. }
  82. }
  83. }
  84.  
  85.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement