早期的版本
class MyActivity :AppCompatActivity, CoroutineScope {
val job = Job()
//指定协程的scope
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
override fun onDestroy() {
job?.cancel()
super.onDestroy()
}
}
更新后的版本 ,在base基类中 只需要简单定义scope
abstract class ScopedAppActivity: AppCompatActivity(), CoroutineScope by MainScope() {
override fun onDestroy() {
super.onDestroy()
cancel() // CoroutineScope.cancel
}
}
class MainActivity : ScopedAppActivity() {
fun asyncShowData() = launch { // Is invoked in UI context with Activity's job as a parent
// actual implementation
}
suspend fun showIOData() {
val deferred = async(Dispatchers.IO) {
// impl
}
withContext(Dispatchers.Main) {
val data = deferred.await()
// Show data in UI
}
}
}
封装异步代码为flow
private fun getSharedPrefFlow() = callbackFlow {
val sharedPref = context?.getSharedPreferences("SHERED_PREF_NAME", MODE_PRIVATE)
sharedPref?.all?.forEach {
offer(it)
}
}
getSharedPrefFlow().collect {
val key = it.key
val value = it.value
}
防点击抖动, 此处的debounce 实际上行为是延迟了500毫秒,和rxjava中的throttlefirst 行为不像,实际上此处使用sample 效果更类似。只不过sample只去500毫秒中最后一个,更像是throttlelast
fun View.clicks(): Flow<Unit> = callbackFlow {
this@clicks.setOnClickListener {
this.offer(Unit)
}
awaitClose { this@clicks.setOnClickListener(null) }
}
button.clicks()
.debounce(500)
.onEach { /*React on a click event*/ }
.launchIn(lifecycleScope)