From 35c7316433a9e533dbe99663ca89ef474939da5e Mon Sep 17 00:00:00 2001 From: Mohsen Rzna Date: Sun, 20 Nov 2022 16:35:50 +0100 Subject: [PATCH] Added two extension functions for StateIn There are two extension functions in this file, one is for ViewModels, and another one for using within a CoroutineScope. --- .../apps/nowinandroid/core/ui/Extenstions.kt | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 core/ui/src/main/java/com/google/samples/apps/nowinandroid/core/ui/Extenstions.kt diff --git a/core/ui/src/main/java/com/google/samples/apps/nowinandroid/core/ui/Extenstions.kt b/core/ui/src/main/java/com/google/samples/apps/nowinandroid/core/ui/Extenstions.kt new file mode 100644 index 000000000..ba0427b79 --- /dev/null +++ b/core/ui/src/main/java/com/google/samples/apps/nowinandroid/core/ui/Extenstions.kt @@ -0,0 +1,45 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.samples.apps.nowinandroid.core.ui + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.stateIn + +/** + * This is a helper extension function to make it easier to use [Flow.stateIn] within a ViewModel. + * @Returns a [StateFlow] that shares the latest value emitted by the original [Flow] and starts + * with the [initialValue]. + */ +fun Flow.stateInViewModelScope( + viewModelScope: CoroutineScope, + started: SharingStarted = SharingStarted.WhileSubscribed(5_000), + initialValue: T +): StateFlow = stateIn(viewModelScope, started, initialValue) + +/** + * This is a helper extension function to make it easier to use [Flow.stateIn] within a [CoroutineScope]. + * @Returns a [StateFlow] that shares the latest value emitted by the original [Flow] and starts + * with the [initialValue]. + */ +fun Flow.stateInCoroutineScope( + viewModelScope: CoroutineScope, + started: SharingStarted = SharingStarted.WhileSubscribed(5_000), + initialValue: T +): StateFlow = stateIn(viewModelScope, started, initialValue)