kotlin--StateFlow运用

StateFlow当值发生变化,就会将值发送出去,下流就可以接收到新值。在某些场景下,StateFlow比LiveData更适用

效果:


1.定义ViewModel

StateFlow需要初始值

package com.aruba.flowapplyapplication.viewmodel

import android.view.View
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

/**
 * Created by aruba on 2021/9/21.
 */
class StateFlowViewModel : ViewModel() {
    val stateFlow = MutableStateFlow(0)

    fun add(v: View) {
        stateFlow.value++
    }

    fun reduce(v: View) {
        stateFlow.value--
    }
}
2.Fragment的布局文件

DataBinding也支持在xml中直接使用StateFlow




    

        

        

        
3.Fragment中绑定ViewModel
package com.aruba.flowapplyapplication

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.aruba.flowapplyapplication.databinding.FragmentStateFlowBinding
import com.aruba.flowapplyapplication.viewmodel.StateFlowViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class StateFlowFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val binding: FragmentStateFlowBinding = DataBindingUtil.inflate(
            inflater,
            R.layout.fragment_state_flow,
            container,
            false
        )

        val stateFlowViewModel = ViewModelProvider(
            this,
            ViewModelProvider.AndroidViewModelFactory(requireActivity().application)
        ).get(StateFlowViewModel::class.java)
//        lifecycleScope.launch {
//            stateFlowViewModel.stateFlow.collect {
//                binding.textView2.text = it.toString()
//            }
//        }
        binding.stateFlowViewModel = stateFlowViewModel
        binding.lifecycleOwner = viewLifecycleOwner

        return binding.root
    }

}
Demo地址:https://gitee.com/aruba/flow-apply-application.git

你可能感兴趣的:(kotlin--StateFlow运用)