All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.com.paoapps.fifi.utils.flow.FlowUtils.kt Maven / Gradle / Ivy

Go to download

Kotlin Multiplatform Mobile framework for optimal code sharing between iOS and Android.

There is a newer version: 0.0.31
Show newest version
package com.paoapps.fifi.utils.flow

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.onStart
import kotlin.time.Duration

fun  Flow.wrap(scope: CoroutineScope): FlowAdapter =
    FlowAdapter(scope, this)

fun  FlowAdapter.distinctUntilChanged(): FlowAdapter = FlowAdapter(scope, flow.distinctUntilChanged())

fun  FlowAdapter.debug(message: String): FlowAdapter = FlowAdapter(scope, internalDebug(message))
fun  Flow.debug(message: String, describeValue: (T) -> (String) = { it.toString() }): Flow = internalDebug(message, describeValue)


private val maxContentLength = 5000
fun  Flow.internalDebug(message: String, describeValue: (T) -> (String) = { it.toString() }): Flow = onStart {
    com.paoapps.fifi.log.debug(
        "Start ${message}"
    )
}.onEach {
    val content = describeValue(it)

    com.paoapps.fifi.log.debug(
        "${message}: $content"
    )
}.onCompletion { exception ->
    com.paoapps.fifi.log.debug(
        "Completed ${message}: $exception"
    )
}

private data class Poll(val delayTime: Duration, val initial: Boolean = false)

// TODO: implement when needed
//fun , D> Flow.poll(
//    delayDuration: Duration = 1.minutes,
//    errorDelayDuration: Duration = 5.seconds,
//    delayFactor: Int = 2
//): Flow {
//    var currentErrorDelay = errorDelayDuration
//    val delayDurationFlow = MutableStateFlow(Poll(delayTime = delayDuration, initial = true))
//    return delayDurationFlow
//        .flatMapLatest { poll ->
//            flow {
//                if (poll.initial) {
//                    emit(Unit)
//                }
//                while(true) {
//                    delay(poll.delayTime)
//                    emit(Unit)
//                }
//            }
//        }
//        .flatMapLatest {
//            this.map {
//                if (it.isFailure) {
//                    delayDurationFlow.value = Poll(currentErrorDelay)
//                    currentErrorDelay *= delayFactor
//                } else if (it.isSuccess) {
//                    delayDurationFlow.value = Poll(delayDuration)
//                    currentErrorDelay = errorDelayDuration
//                }
//                it
//            }
//        }
//}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy