当我在 Kotlin 中使用 Compose 时,从 Flow 进行收集的操作会消耗大量系统资源吗?

2023-12-28

The SoundViewModel is a ViewModel类,以及val listSoundRecordState可能会被应用程序中的某些模块使用。

在代码 A 中,我调用fun collectListSoundRecord()当我需要使用数据时listSoundRecordState. But fun collectListSoundRecord()可能会因为Jetpack Compose重新组合而反复启动,不知道会不会消耗很多系统资源?

在代码 B 中,我启动private fun collectListSoundRecord() in init { }, collectListSoundRecord()将仅启动一次,但即使我不需要使用数据,它也会保留在内存中,直到应用程序代码关闭listSoundRecordState,这种方式会消耗很多系统资源吗?

Code A

@HiltViewModel
class SoundViewModel @Inject constructor(
  ...
): ViewModel() {

    private val _listSoundRecordState = MutableStateFlow<Result<List<MRecord>>>(Result.Loading)
    val listSoundRecordState = _listSoundRecordState.asStateFlow()

    init { }

     //It may be launched again and again
    fun collectListSoundRecord(){
        viewModelScope.launch {
            listRecord().collect {
                result -> _listSoundRecordState.value =result
            }
        }
    }

    private fun listRecord(): Flow<Result<List<MRecord>>> {
        return  aSoundMeter.listRecord()
    }

}

Code B

@HiltViewModel
class SoundViewModel @Inject constructor(
  ...
): ViewModel() {

    private val _listSoundRecordState = MutableStateFlow<Result<List<MRecord>>>(Result.Loading)
    val listSoundRecordState = _listSoundRecordState.asStateFlow()

    init { collectListSoundRecord() }

    private fun collectListSoundRecord(){
        viewModelScope.launch {
            listRecord().collect {
                result -> _listSoundRecordState.value =result
            }
        }
    }

    private fun listRecord(): Flow<Result<List<MRecord>>> {
        return  aSoundMeter.listRecord()
    }

}

您可能会受益于收集原始流(来自listRecord())仅当您的中间流有订阅者时(您保留在您的中间流中的订阅者)SoundViewModel)并缓存结果。

就您而言,订户将是Composable收集值的函数(并且可能经常重组)。

您可以使用非暂停变体来实现这一点stateIn() https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/state-in.html,因为你有一个默认值。

@HiltViewModel
class SoundViewModel @Inject constructor(
    ...
): ViewModel() {

    val listSoundRecordState = listRecord().stateIn(viewModelScope, SharingStarted.WhileSubscribed(), Result.Loading)

    private fun listRecord(): Flow<Result<List<MRecord>>> {
        return  aSoundMeter.listRecord()
    }
}

为了使用StateFlow从 UI 层(@Composable函数),你必须将其转换为State,像这样:

val viewModel: SoundViewModel = viewModel()
val listSoundRecord = viewModel.listSoundRecordState.collectAsState()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当我在 Kotlin 中使用 Compose 时,从 Flow 进行收集的操作会消耗大量系统资源吗? 的相关文章

随机推荐