一、AppCompatActivity实现CoroutineScope接口:
class Test1Activity : AppCompatActivity(), CoroutineScope {
private lateinit var job: Job
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
job = Job()
test()
}
private fun test() {
launch {
val result = withContext(Dispatchers.IO) {
delay(1000)
"0"
}
Log.d("result", result)
}
}
override fun onDestroy() {
super.onDestroy()
job.cancel()
}
}
二、直接实例化MainScope:
class Test2Activity : AppCompatActivity() {
private val mailScope = MainScope()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
test()
}
private fun test() {
mailScope.launch {
val result = withContext(Dispatchers.IO) {
delay(1000)
"0"
}
Log.d("result", result)
}
}
override fun onDestroy() {
super.onDestroy()
mailScope.cancel()
}
}
三、导入implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.0-alpha02',就可以直接在AppCompatActivity调用lifecycleScope:
class Test3Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
test()
}
private fun test() {
lifecycleScope.launch {
val result = withContext(Dispatchers.IO) {
delay(1000)
"0"
}
Log.d("result", result)
}
}
override fun onDestroy() {
super.onDestroy()
lifecycleScope.cancel()
}
}
最后发一下使用协程和RxJava的代码量和可读性对比:
协程:
dialog.show()
lifecycleScope.launch {
val result = withContext(Dispatchers.IO) {
sendHtmlMail()
}
dialog.dismiss()
if (result == OK) {
makeText(this@EmailReplyActivity, getString(R.string.mail_send_success_hint))
finish()
} else if (result == ERR) {
makeText(this@EmailReplyActivity, getString(R.string.mail_send_fail_hint))
}
}
RxJava:
dialog.show()
Observable.create { emitter: ObservableEmitter<String?> ->
val result = sendHtmlMail()
emitter.onNext(result)
emitter.onComplete()
}.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Observer<String?> {
override fun onSubscribe(d: Disposable) {
compositeDisposable.add(d)
}
override fun onNext(value: String?) {
if (value.equals(OK)) {
makeText(this@EmailReplyActivity, getString(R.string.mail_send_success_hint))
finish()
} else if (value.equals(ERR)) {
makeText(this@EmailReplyActivity, getString(R.string.mail_send_fail_hint))
}
}
override fun onError(e: Throwable) {
dialog.dismiss()
e.printStackTrace()
}
override fun onComplete() {
dialog.dismiss()
}
})
突然觉得RxJava很恶心有没有