基于Kotlin Flow的Andoird线程通信工具
标签搜索

基于Kotlin Flow的Andoird线程通信工具

Pop.Kite
2023-03-24 / 2 评论 / 118 阅读 / 正在检测是否收录...
/**
 * 能够感知生命周期的数据流处理类
 */
class DataHelper : CoroutineScope by CoroutineScope(Dispatchers.IO + SupervisorJob()),
    DefaultLifecycleObserver {

    companion object {
        private const val TAG = "DataHelper"
        val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { DataHelper() }
    }

    private var mLifecycle: Lifecycle? = null

    /**
     * lifecycle should keep immutable and unique
     */
    fun <T> setLifecycle(clazz: Class<T>, lifecycle: Lifecycle) {
        Log.i(TAG, "$clazz initialized lifecycle: ")
        if (mLifecycle == null) {
            mLifecycle = lifecycle
            mLifecycle?.addObserver(this)
        } else {
            if (lifecycle == mLifecycle) {
                return
            } else {
                throw java.lang.RuntimeException("LifeCycle cannot be set by $clazz more than once!")
            }
        }
    }

    /**
     * SharedFlowMap, every Class has own sharedFlow,cache size default is one
     */
    private val mShareFlowDataMap = mutableMapOf<Class<*>, MutableSharedFlow<Any>>()

    /**
     * StateFlow,like SharedFlowMap,support deBounce
     */
    private val mStateFlowDataMap = mutableMapOf<Class<*>, MutableStateFlow<Any>>()

    /**
     * sharedFlow emit data
     * [T] customized object
     */
    fun <T : Any> postSharedFlow(t: T) {
        Log.e(TAG, "postSharedFlow: ${t.javaClass}")
        launch {
            if (!mShareFlowDataMap.containsKey(t.javaClass)) {
                mShareFlowDataMap[t.javaClass] = MutableSharedFlow(1)
            }
            mShareFlowDataMap[t.javaClass]?.emit(t)
            cancel()
        }
    }


    /**
     * sharedFlow collect data
     * [t] customized class
     * [block] the function to use result,support suspend
     */
    fun <T : Any> collectSharedFlow(t: Class<T>, block: suspend (T) -> Unit) {
        Log.e(TAG, "collectSharedFlow: $t")
        launch {
            if (!mShareFlowDataMap.containsKey(t)) {
                mShareFlowDataMap[t] = MutableSharedFlow(1)
            }

            mLifecycle?.repeatOnLifecycle(Lifecycle.State.RESUMED) {
                mShareFlowDataMap[t]?.collect {
                    block.invoke(it as T)
                }
            }
                ?: mShareFlowDataMap[t]?.collect {
                    block.invoke(it as T)
                }
            cancel()
        }
    }

    /**
     * stateFlow emit data
     * [T] customized object
     */
    fun <T : Any> postStateFlow(t: T) {
        Log.i(TAG, "postStateFlow: ${t.javaClass}")
        launch {
            if (!mStateFlowDataMap.containsKey(t.javaClass)) {
                mStateFlowDataMap[t.javaClass] = MutableStateFlow("")
            }
            mStateFlowDataMap[t.javaClass]?.emit(t)
            cancel()
        }
    }

    /**
     * stateFlow collect data
     * [t] customized class
     * [block] the function to use result,support suspend
     */
    fun <T : Any> collectStateFlow(t: Class<T>, block: suspend (T) -> Unit) {
        Log.i(TAG, "collectStateFlow: $t")
        launch {
            mLifecycle?.repeatOnLifecycle(Lifecycle.State.RESUMED) {
                mStateFlowDataMap[t]?.collect {
                    block.invoke(it as T)
                }
            }
                ?: mStateFlowDataMap[t]?.collect {
                    block.invoke(it as T)
                }
            cancel()
        }
    }

    override fun onStart(owner: LifecycleOwner) {
        super.onStart(owner)
        Log.e(TAG, "onStart: ")
    }

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        Log.e(TAG, "onResume: ")
    }

    /**
     * Check whether the current [clazz] Type exists in the Map
     */
    private fun <T> checkExistShareFlow(clazz: Class<T>) {
        if (!mShareFlowDataMap.containsKey(clazz)) {
            mShareFlowDataMap[clazz] = MutableSharedFlow(1)
            Log.w(TAG, "checkExistShareFlow: Create New One")
        } else {
            Log.w(TAG, "checkExistShareFlow: Exist")
        }
    }

    /**
     * Check whether the current [clazz] Type exists in the Map
     */
    private fun <T> checkExistStateFlow(clazz: Class<T>) {
        if (!mStateFlowDataMap.containsKey(clazz)) {
            mStateFlowDataMap[clazz] = MutableStateFlow("")
            Log.w(TAG, "checkExistStateFlow: Create New One")
        } else {
            Log.w(TAG, "checkExistStateFlow: Exist")
        }
    }

    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
        mLifecycle = null
        Log.e(TAG, "onDestroy: ")
    }
}
0

评论 (2)

取消
  1. 头像
    aka
    Android · Google Chrome

    画图

    回复
    1. 头像
      popkter 作者
      MacOS · Safari
      @ aka

      表情

      回复