I am working on a program which has both a TUI (terminal user interface) as well as a GUI (graphical user interface).
The program has some functions which take quite a long time to complete (waiting on network requests and such). I know that I can use threads (or coroutines since I am using Kotlin) to have the long running task in the background, while the TUI or GUI does other things. However, I also have information that I want to convey while the task is running, so the user knows what's happening in the mean time (as opposed to just showing "Loading..." or a spinning circle icon).
My current guess is to use something like callbacks (or Channel
in Kotlin) to convey information, like "I am now doing X", "I have completed X", "I failed to do X so I am now aborting", etc. I have given an example of my current idea below. Is this solution okay, or am I fundamentally missing something? Are there ways the code sample I gave could be improved?
suspend fun foo(
/* other parameters here */
eventChannel: Channel<FooEvent>,
) {
eventChannel.send(FooEvent.BeginBar())
try {
/* do work that may fail here */
eventChannel.send(FooEvent.FinishBar())
} catch (e: Exception) {
eventChannel.send(FooEvent.FailBar(e))
return
}
eventChannel.send(FooEvent.BeginBaz())
try {
/* do work that may fail here */
eventChannel.send(FooEvent.FinishBaz())
} catch (e: Exception) {
eventChannel.send(FooEvent.FailBaz(e))
return
}
}
sealed class FooEvent {
class BeginBar : FooEvent()
class FailBar(cause: Throwable) : FooEvent()
class FinishBar : FooEvent()
class BeginBaz : FooEvent()
class FailBaz(cause: Throwable) : FooEvent()
class FinishBaz : FooEvent()
}