Joakim Forslund
10/13/2021, 1:01 PMenum class RandomServiceState {
INIT,
CREATED,
DESTROYED
}
class RandomServiceMonitor(
val context: Context,
val lifecycleCoroutineScope: ManagedCoroutineScope,
val binderToRecreate: IBinder? = ServiceManager.getService(
SERVICE_NAME
),
var currentState: RandomServiceState = RandomServiceState.INIT,
private val flow: MutableSharedFlow<RandomServiceState> = MutableSharedFlow(
replay = 1,
extraBufferCapacity = 0,
onBufferOverflow = BufferOverflow.SUSPEND
),
val sharedFlow: SharedFlow<RandomServiceState> = flow.shareIn(
lifecycleCoroutineScope,
SharingStarted.Lazily
),
private
var binder: IBinder? = binderToRecreate
) {
companion object {
const val SERVICE_NAME = "random.service";
}
val deathRecipient = IBinder.DeathRecipient {
binder = null
flow.tryEmit(RandomServiceState.DESTROYED)
currentState = RandomServiceState.DESTROYED
}
init {
bind()
}
fun bind() {
if (binder == null) {
binder = binderToRecreate
}
binder?.let { it ->
it.linkToDeath(deathRecipient, 1)
currentState = RandomServiceState.CREATED
flow.tryEmit(currentState)
}
}
}
Hi, I'm trying to make a monitor class that should reboot an android service binding with Flow. Everything works great until I want to actually restart everything with running the bind()
method again when we reach state DESTROYED. If I run that method in the deathRecipient part of the code, collectors will never get the state DESTROYED, but rather CREATED. How is this solvable with SharableFlow ?