一 Flow运用留意事项

多个Flow不能放到一个lifecycleScope.launch里去collect{},因为进入collect{}相当于一个死循环,下一行代码永远不会履行;如果就想写到一个lifecycleScope.launch{}里去,能够在内部再敞开launch{}子协程去履行。

示例,下面是过错写法

  //NOTE: 下面的示例是过错写法
  lifecycleScope.launch { 
        mFlowModel.caseFlow1
            .flowWithLifecycle(lifecycle, Lifecycle.State.STARTED)
            .collect {}
        mFlowModel.caseFlow2
            .flowWithLifecycle(lifecycle, Lifecycle.State.STARTED)
            .collect {}
  }

正确写法:

  lifecycleScope.launch {
        launch {
            mFlowModel.caseFlow1
                .flowWithLifecycle(lifecycle, Lifecycle.State.STARTED)
                .collect {}
       }

        launch {
            mFlowModel.caseFlow2
                .flowWithLifecycle(lifecycle, Lifecycle.State.STARTED)
                .collect {}
        }
    }

当然,直接启动多个 lifecycleScope.launch也是能够的。

二 几种运用场景

2.1、处理杂乱、耗时逻辑

一般在处理杂乱逻辑、耗时操作时,咱们会将其放到子线程中去处理,防止在主线程中处理导致卡顿。而Flow能够方便地进行线程切换,所以处理杂乱逻辑、耗时操作时,能够考虑运用Flow来进行处理,下面来看一个比如:

假设咱们想读取本地Assets目录下的person.json文件,并将其解析出来,json文件中的内容

// assets目录下person.json
{
	"name": "小马快跑",
	"age": 18,
	"interest": "money! lots of money!"
}

下面经过Flow的方法完成在IO线程中读取json文件,并终究在主线程中输出成果:

/**
 * 经过Flow方法,获取本地文件
 */
 private fun getFileInfo() {
      lifecycleScope.launch {
            flow {
                //解析本地json文件,并生成对应字符串
                val configStr = getAssetJsonInfo(requireContext(), "person.json")
                //最后将得到的实体类发送到下流
                emit(configStr)
            }
                .map { json ->
                    Gson().fromJson(json, PersonModel::class.java) //经过Gson将字符串转为实体类
                }
                .flowOn(Dispatchers.IO) //在flowOn之上的一切操作都是在IO线程中进行的
                .onStart { log("onStart") }
                .filterNotNull()
                .onCompletion { log("onCompletion") }
                .catch { ex -> log("catch:${ex.message}") }
                .collect {
                    log("collect parse result:$it")
                }
        }
  }
/**
 * 读取Assets下的json文件
 */
private fun getAssetJsonInfo(context: Context, fileName: String): String {
        val strBuilder = StringBuilder()
        var input: InputStream? = null
        var inputReader: InputStreamReader? = null
        var reader: BufferedReader? = null
        try {
            input = context.assets.open(fileName, AssetManager.ACCESS_BUFFER)
            inputReader = InputStreamReader(input, StandardCharsets.UTF_8)
            reader = BufferedReader(inputReader)
            var line: String?
            while ((reader.readLine().also { line = it }) != null) {
                strBuilder.append(line)
            }
        } catch (ex: Exception) {
            ex.printStackTrace()
        } finally {
            try {
                input?.close()
                inputReader?.close()
                reader?.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    return strBuilder.toString()
}

履行成果:

11:11:32.178  E  onStart
11:11:32.197  E  collect parse result:PersonModel(name=小马快跑, age=18, interest=money! lots of money!)
11:11:32.198  E  onCompletion

能够看到在collect{}中得到了正确的数据,这儿留意一下flowOn()的作用域是在本身之上的操作,上述比如中flowOn(Dispatchers.IO) 意味着在flowOn之上的一切操作都是在IO线程中进行的。

2.2、存在依靠联系的接口恳求

如果终究展现依靠多个接口且接口之间是有依靠联系的,之前咱们可能会在第一个接口恳求成功的回调里持续调用第二个接口,以此类推,这样尽管能完成,可是会导致回调层级很深,也就是所谓的回调地狱;此时能够运用FlowflatMapConcat将多个接口串联起来。

lifecycleScope.launch {
     lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
                 //将两个flow串联起来 先搜索目的地,然后到达目的地
                mFlowModel.getSearchFlow()
                    .flatMapConcat {
                        //第二个flow依靠第一个的成果
                        mFlowModel.goDestinationFlow(it)
                    }.collect {
                        mTvCallbackFlow.text = it ?: "error"
                    }
     }
}

2.3、组合多个接口的数据

有这样一种场景:数据的终究展现依靠多个接口恳求到的数据,有两种完成方法:

  • 一个个串行去恳求接口,拿到数据后终究拼到一同;
  • 一切接口并行去恳求,拿到数据后终究拼到一同。

串行恳求尽管能够,可是功率并不高;更优的方法是采用接口并行,能够运用Flowzip操作符,如下要获取电费、水费、网费的总花销,对应的花费需求各自恳求自己的接口,终究把数据进行兼并统计:

  //ViewModel中
  //分别恳求电费、水费、网费,Flow之间是并行联系
  suspend fun requestElectricCost(): Flow<ExpendModel> =
        flow {
            delay(500)
            emit(ExpendModel("电费", 10f, 500))
        }.flowOn(Dispatchers.IO)
  suspend fun requestWaterCost(): Flow<ExpendModel> =
        flow {
            delay(1000)
            emit(ExpendModel("水费", 20f, 1000))
        }.flowOn(Dispatchers.IO)
  suspend fun requestInternetCost(): Flow<ExpendModel> =
        flow {
            delay(2000)
            emit(ExpendModel("网费", 30f, 2000))
        }.flowOn(Dispatchers.IO)
  data class ExpendModel(val type: String, val cost: Float, val apiTime: Int) {
    fun info(): String {
        return "${type}: ${cost}, 接口恳求耗时约$apiTime ms"
    }
}
    //UI层
    mBtnZip.setOnClickListener {
        lifecycleScope.launch {
            val electricFlow = mFlowModel.requestElectricCost()
            val waterFlow = mFlowModel.requestWaterCost()
            val internetFlow = mFlowModel.requestInternetCost()
            val builder = StringBuilder()
            var totalCost = 0f
            val startTime = System.currentTimeMillis()
            //NOTE:留意这儿能够多个zip操作符来兼并Flow,且多个Flow之间是并行联系
            electricFlow.zip(waterFlow) { electric, water ->
                totalCost = electric.cost + water.cost
                builder.append("${electric.info()},\n").append("${water.info()},\n")
            }.zip(internetFlow) { two, internet ->
                totalCost += internet.cost
                two.append(internet.info()).append(",\n\n总花费:$totalCost")
            }.collect {
                mTvZipResult.text = it.append(",总耗时:${System.currentTimeMillis() - startTime} ms")
            }
        }
    }

履行成果:

电费: 10.0, 接口恳求耗时约500 ms,
水费: 20.0, 接口恳求耗时约1000 ms,
网费: 30.0, 接口恳求耗时约2000 ms,
总花费:60.0,总耗时:2012 ms

能够看到不光得到了一切接口的数据,并且总耗时基本等于耗时最长的接口的时间,阐明zip操作符兼并的多个Flow内部接口恳求是并行的。