kotlinx.coroutines icon indicating copy to clipboard operation
kotlinx.coroutines copied to clipboard

Kotlin coroutine `.asFlow()` pair with RxJava `.observeOn(AndroidSchedulers.mainThread())` will block app

Open fightyz opened this issue 3 years ago • 0 comments
trafficstars

This error seems to only appear on my Huawei Honor 10 (COL-AL10 HarmonyOS 2.0.0). The mobile phone(other mobile phones do not) system will stop all the threads of the app after the app has returned to the background for a period of time (more than ten seconds), and when the app returns to the foreground again, the system will continue to run the threads.

case 1: Just use .asFlow() in Android without problems:

val observableInterval = Observable.interval(10, TimeUnit.MILLISECONDS)

uiScope.launch {
    observableInterval
        .asFlow()
        .onEach {
            Log.d("jojo", "interval: $it")
        }.launchIn(this)
}

image

case 2: But if I use .observeOn(AndroidSchedulers.mainThread()), when the app comes back to the foreground, the counter is stopped after emitting a limited number of data, and the whole app is stuck (but no ANR):

val observableInterval = Observable.interval(10, TimeUnit.MILLISECONDS)
		.observeOn(AndroidSchedulers.mainThread())

uiScope.launch {
    observableInterval
        .asFlow()
        .onEach {
            Log.d("jojo", "interval: $it")
        }.launchIn(this)
}

image

case 3: If I add .toFlowable(BackpressureStrategy.LATEST), the app behaves like case 1 again:

val observableInterval = Observable.interval(10, TimeUnit.MILLISECONDS)
		.observeOn(AndroidSchedulers.mainThread())

uiScope.launch {
    observableInterval
				.toFlowable(BackpressureStrategy.LATEST)
        .asFlow()
        .onEach {
            Log.d("jojo", "interval: $it")
        }.launchIn(this)
}

My dev environment: System: HarmonyOS 2.0.0 Dependencies:

implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.6.21'
implementation 'io.reactivex.rxjava2:rxjava:2.2.21'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-rx2:1.6.1'

fightyz avatar May 01 '22 14:05 fightyz