Skip to content

Commit 88be367

Browse files
committed
added example of MutableStateFlow
1 parent d499d15 commit 88be367

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.monstarlab.features.sample
2+
3+
import android.os.Bundle
4+
import android.view.LayoutInflater
5+
import android.view.View
6+
import android.view.ViewGroup
7+
import androidx.fragment.app.Fragment
8+
import com.monstarlab.R
9+
import com.monstarlab.base.BaseFragment
10+
import com.monstarlab.databinding.FragmentSampleBinding
11+
import com.monstarlab.extensions.collectFlow
12+
13+
class SampleFragment: BaseFragment(R.layout.fragment_sample) {
14+
15+
val viewModel by viewModel<SampleViewModel>()
16+
17+
private var _binding: FragmentSampleBinding? = null
18+
private val binding get() = _binding!!
19+
20+
override fun onCreateView(
21+
inflater: LayoutInflater,
22+
container: ViewGroup?,
23+
savedInstanceState: Bundle?
24+
): View? {
25+
_binding = FragmentSampleBinding.inflate(inflater, container, false)
26+
val view = binding.root
27+
return view
28+
}
29+
30+
override fun onDestroyView() {
31+
super.onDestroyView()
32+
_binding = null
33+
}
34+
35+
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
36+
super.onViewCreated(view, savedInstanceState)
37+
38+
collectFlow(viewModel.clickFlow) { clicks ->
39+
binding.valueTextView.text = "Clicked $clicks times"
40+
}
41+
42+
binding.theButton.setOnClickListener {
43+
viewModel.clickedButton()
44+
}
45+
}
46+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.monstarlab.features.sample
2+
3+
import androidx.lifecycle.ViewModel
4+
import kotlinx.coroutines.flow.MutableStateFlow
5+
import javax.inject.Inject
6+
7+
class SampleViewModel @Inject constructor(
8+
9+
): ViewModel() {
10+
11+
val clickFlow: MutableStateFlow<Int> = MutableStateFlow(0)
12+
13+
fun clickedButton() {
14+
clickFlow.value++
15+
}
16+
17+
}

0 commit comments

Comments
 (0)