本文介绍了如何用Flow替换LiveData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为sortOrderLiveData,然后有另一个名为myData的变量,它观察到sortOrder的任何变化并相应地填充数据.

I've one LiveData named sortOrder and then I've another variable named myData that observes any change to sortOrder and populates data accordingly.

class TestViewModel @ViewModelInject constructor() : ViewModel() {

    private val sortOrder = MutableLiveData<String>()

    val myData = sortOrder.map {
        Timber.d("Sort order changed to $it")
        "Sort order is $it"
    }

    init {
        sortOrder.value = "year"
    }

}

观察活动

class TestActivity : AppCompatActivity() {

    private val viewModel: TestViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test)

        // Observing data
        viewModel.myData.observe(this) {
            Timber.d("Data is : $it")
        }
    }
}

问题

  • 如何在不更改输出的情况下用Flow/StateFlow API替换上述情况?
  • How can I replace the above scenario with Flow/StateFlow APIs without any change in output?

推荐答案

如果您无法将映射的冷流程转换为热流程,则每次收集该流程时,它将重新启动该流程(例如重新创建Activity时).这就是冷流的工作方式.

If you fail to convert the mapped cold Flow into a hot Flow, it will restart the flow every time you collect it (like when your Activity is recreated). That's how cold flows work.

我有一种感觉,他们会充实StateFlow/SharedFlow的转换函数,因为将它们映射为冷流并将其重新转换为热流感到很尴尬.

I have a feeling they will flesh out the transform functions for StateFlow/SharedFlow, because it feels very awkward to map them to cold flows and have to turn them back into hot flows.

如果您不想明确地手动映射第一个元素,则公共流程必须是SharedFlow,因为stateIn函数要求您直接提供初始状态.

The public Flow has to be a SharedFlow if you don't want to manually map the first element distinctly because the stateIn function requires you to directly provide an initial state.

    private val sortOrder = MutableStateFlow("year")

    val myData = sortOrder.map {
        Timber.d("Sort order changed to $it")
        "Sort order is $it"
    }.shareIn(viewModelScope, SharingStarted.Eagerly, 1)

或者您可以创建在map中以及在stateIn函数调用中调用的单独函数.

Or you could create a separate function that is called within map and also in a stateIn function call.

    private val sortOrder = MutableSharedFlow<String>()

    private fun convertSortOrder(order: String): String {
        Log.d("ViewModel", "Sort order changed to $order")
        return "Sort order is $order"
    }

    val myData = sortOrder.map {
        convertSortOrder(it)
    }.stateIn(viewModelScope, SharingStarted.Eagerly, convertSortOrder("year"))

这篇关于如何用Flow替换LiveData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 21:30