Skip to content

Instantly share code, notes, and snippets.

@SeongUgJung
Last active February 15, 2024 16:38
Show Gist options
  • Save SeongUgJung/49922ff7d888f1ac7bbfeddaa98bfc7b to your computer and use it in GitHub Desktop.
Save SeongUgJung/49922ff7d888f1ac7bbfeddaa98bfc7b to your computer and use it in GitHub Desktop.
@Composable fun LifecycleObservable.observeLifecycle() {
val lifecycleOwner = LocalLifecycleOwner.current
LaunchedEffect(lifecycleOwner) {
var createdJob: Job? = null
var startedJob: Job? = null
var resumedJob: Job? = null
lifecycleOwner.addObserver {
fun onCreated() = createdToDestroy().launchIn(this@LaunchedEffect).let { createdJob = it }
fun onStarted() = startedToStop().launchIn(this@LaunchedEffect).let { startedJob = it }
fun onResumed() = resumedToPaused().launchIn(this@LaunchedEffect).let { resumedJob = it }
fun onPaused() = resumedJob?.takeIf { it.isActive }?.cancel()
fun onStopped() = startedJob?.takeIf { it.isActive }?.cancel()
fun onDestroyed() = createdJob?.takeIf { it.isActive }?.cancel()
}
}
}
interface LifecycleObservable {
fun createdToDestroy(): Flow<*> = emptyFlow()
fun startedToStop(): Flow<*> = emptyFlow()
fun resumedToPaused(): Flow<*> = emptyFlow()
}
class FooViewModel(val chatRepo: ChatRepo): ViewModel(), LifecycleObservable {
private val newMessageToast = mutableStateOf("")
private val newMessages = mutableStateOf(emptyList<Message>())
override fun resumedToPaused() = observeNewChatMessage()
fun observeChatMessage() = chatRepo.observeNewMessage()
.flowOn(IO)
.onEach { newMessage ->
newMessages.value = newMessages.value + newMessage
newMessageToast.value = "received new message : {newMessage.content}"
}
.flowOn(Main)
}
@Composable
fun FooScreen(viewModel: FooViewModel) {
viewModel.observeLifecycle()
val toast = remeber { viewModel.newMessageToast }
val newMessages = remember { viewModel.newMessages }
// TODO show toast and messages
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment