class FTPClientLiveData : BaseLiveDate<FTPClient>() {
override fun onActive() {
val coroutineResult = value
if (coroutineResult == null || coroutineResult.status != CoroutineResult.Status.LOADING ||
(coroutineResult.data != null && coroutineResult.error == null && !coroutineResult.data.isConnected)
) {
runCoroutine(this) {
return@runCoroutine FtpBrowserInteractor.connect(
App.instance.appPref.ftpServer,
App.instance.appPref.ftpPort,
App.instance.appPref.ftpLogin,
App.instance.appPref.ftpPassword
)
}
}
}
override fun onInactive() {
val coroutineResult = value
coroutineResult?.let {
if (coroutineResult.data != null) {
try {
coroutineResult.data.logout()
coroutineResult.data.disconnect()
} catch (e: Throwable) {
e.printStackTrace()
}
}
}
}
override fun setValue(value: CoroutineResult<FTPClient>?) {
//no external setting
}
}
open class BaseLiveDate<T> : MutableLiveData<CoroutineResult<T>>() {
protected fun <T> runCoroutine(resultLiveData: MutableLiveData<CoroutineResult<T>>, block: suspend () -> T) {
value = CoroutineResult(
CoroutineResult.Status.LOADING,
null,
null
)
GlobalScope.launch(Dispatchers.IO) {
try {
val result = block()
resultLiveData.postValue(
CoroutineResult(
CoroutineResult.Status.COMPLETED,
result,
null
)
)
} catch (exception: Exception) {
resultLiveData.postValue(
CoroutineResult(
CoroutineResult.Status.COMPLETED,
null,
exception
)
)
}
}
}
}