Git Product home page Git Product logo

compose-state-events's Introduction

JitPack GitHub GitHub top language


Compose-State-Events

A new way to implement One-Time-UI-Events (former SingleLiveEvent) in a Compose world.

This library will help you to avoid implementing any antipatterns regarding One-Time-UI-Events as despribed by Manuel Vivo's article.

See the samples below on how to effectively use StateEvent in your view's state and EventEffect in your composables.

To get an in depth idea on how to migrate see this article from Yanneck Reiß.

How to use

Imagine a simple usecase where you need to fetch some list data from an API and display the result on the screen.

View State Object

data class FlowerViewState(
    val flowers: List<Flower> = emptyList(),
    val isLoadingFlowers: Boolean = false,
    val downloadSucceededEvent: StateEvent = consumed,
    val downloadFailedEvent: StateEventWithContent<Int> = consumed()
)

Imagine we would like to show a green success snackbar or a red failure snackbar after the loading has finished. These two events would be represented with the two new fields downloadSucceededEvent and downloadFailedEvent in our view state object.

Use the StateEventWithContent<T> when you need to pass some data to the consumer (the composable). In the example above a StringRes with a fitting error description is passed.

ViewModel

private val _stateStream = MutableStateFlow(FlowerViewState())
val stateStream = _stateStream.asStateFlow()

private var state: FlowerViewState
    get() = _stateStream.value
    set(newState) {
        _stateStream.update { newState }
    }
    
fun loadFlowers(){
  viewModelScope.launch {
    state = state.copy(isLoading = true)
    state = when (val apiResult = loadAllFlowersFromApiUseCase.call()) {
        is Success -> state.copy(flowers = apiResult, downloadSucceededEvent = triggered)
        is Failure -> state.copy(downloadFailedEvent = triggered(R.string.error_load_flowers))
    }
    state = state.copy(isLoading = false)
  }
}

fun onConsumedDownloadSucceededEvent(){
  state = state.copy(downloadSucceededEvent = consumed)
}

fun onConsumedDownloadFailedEvent(){
  state = state.copy(downloadFailedEvent = consumed())
}

To trigger an event without any data just use the triggered value, otherwise use the triggered(content: T) function. To consume an event without any data just use the consumed value, otherwise use the consumed() function.

Composable

val viewModel: MainViewModel = viewModel()
val viewState: MainViewState by viewModel.stateStream.collectAsStateLifecycleAware()

EventEffect(
    event = viewState.downloadSucceededEvent, 
    onConsumed = viewModel::onConsumedDownloadSucceededEvent
) {
    scaffoldState.snackbarHostState.showSnackbar("Download succeeded.")
}

EventEffect(
    event = viewState.downloadFailedEvent, 
    onConsumed = viewModel::onConsumedDownloadFailedEvent
) { stringRes ->
    scaffoldState.snackbarHostState.showSnackbar(context.resources.getString(stringRes))
}

The EventEffect is a LaunchedEffect that will be executed, when the event is in its triggered state. When the event action was executed the effect calls the passed onConsumed callback to force you to set the view state field to be consumed.

Special Case: Navigation

In the regular way you only want to consume your event when it really got processed. However, in some special cases you want to make sure that the StateEvent gets consumed no matter what the outcome of your code that gets triggered will be. One case in which that gets relevant is when you want to navigate to another screen, if a StateEvent or StateEventWithContent<T> got invoked.

For this special case, instead of EventEffect, you can use the NavigationEventEffect.

NavigationEventEffect(  
  event = viewState.downloadFailedEvent,  
  onConsumed = viewModel::onConsumedDownloadFailedEvent  
) {
  navigator.navigateBack()  
}

Installation

allprojects {
   repositories {
       ...
       maven { url "https://jitpack.io" }
   }
}
dependencies {
   implementation 'com.github.leonard-palm:compose-state-events:2.2.0'
}

compose-state-events's People

Contributors

alton09 avatar leonard-palm avatar octa-one avatar yanneckreiss avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

compose-state-events's Issues

Action for EventEffect or NavigationEffect is called twice per trigger.

Hi. Thank you for this library! Noticed a possible bug where the action for an EventEffect or NavigationEventEffect is called twice when triggered. This happens when the onConsumed parameter is set with a lambda. I think this is a valid way to use the effects, but I'm not sure. Can you let me know your thoughts? Thanks again

val screenState by viewModel.screenState.collectAsStateWithLifecycle()

// The action for this effect is called twice per trigger.
NavigationEventEffect(
    event = screenState.closeEvent,
    onConsumed = { viewModel.onConsumeCloseEvent() }
) {
    navController.popBackStack()
}

// The action for this version is called just once as expected.
NavigationEventEffect(
    event = screenState.closeEvent,
    onConsumed = viewModel::onConsumeCloseEvent
) {
    navController.popBackStack()
}

// View Model
private val _screenState = MutableStateFlow(initialState)
val screenState = _screenState.asStateFlow()

...

fun onCloseClick() {
    _screenState.update { it.copy(closeEvent = triggered) }
}

fun onConsumeCloseEvent() {
    _screenState.update { it.copy(closeEvent = consumed) }
}

A possible fix for this is to remove the onConsumed parameter from the keys on the LaunchedEffect within NavigationEventEffect and EventEffect.

Mark StateEvent(WithContent) as Stable/Immutable

Hi,

I'm wondering what your thoughts are about marking the StateEvent / StateEventWithContent and its implementation as either Stable or Immutable. I think both are applicable (though Immutable should be more fitting) and would enable the Composables where those types are used to be skippable.

Any thoughts on this?

As reference: Jetpack Compose Stability Explained

How is the library used together with paging3?

I have a Room DAO that has the following query. My ViewModel then defines the Pager instance I use inside my ViewModel as shown below:

/// DAO
@Query("SELECT * FROM <table> ORDER BY createdAt DESC")
fun getAllPaged(): PagingSource<Int, Model>

/// ViewModel
class MyViewModel: ViewModel() {
    val allItems = Pager(PagingConfig(pageSize = 10)) {
        myDao.getAllPaged()
    }.flow.cachedIn(viewModelScope)
}

/// UI
@Composable
fun MyContent(viewModel: MyViewModel = hiltViewModel()) {
    val items = viewModel.allItems.collectAsLazyPagingItems()
}

How do I keep the Pager lazy when adding it to the ViewState data class? I don't know if this is possible and by checking online I don't think it is.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.