How to Read All the Text From a File and Close It C++

A Jetpack Compose Tutorial for Beginners – How To Understand Composables & Recomposition

This tutorial will teach yous a few cardinal concepts and terms related to the Jetpack Compose UI Library on Android.

While this is a beginner'south guide to Etch, it volition not be a beginner's guide to Android – and so you lot should accept built at least an application or two (though not in Compose, necessarily).

Before we begin, I was initially planning to write a follow upward article directed towards more than senior developers until I came across Leland Richardson's 2 part article serial. Leland is not simply a Software Engineer working on the Jetpack Compose team, but I come across that he is a great writer as well.

While I feel my commodity will stand on its own as an introduction to the basics of Jetpack Etch, I strongly suggest you read his articles one time you take gained some practical experience with Etch (or right away if you lot prefer to learn that way).

Key Terms/Concepts Explained in this article:

  • A cursory review of the onetime View Organization and Hierarchy
  • Composables and how they stand in relation to Views
  • Recomposition and how to avoid doing information technology very poorly!

What Is A Composable?

In this department, we volition talk over the most cardinal part of the Jetpack Compose library. If you are a seasoned Android developer, you may wish to skip to the sub-department titled "Are Composables Views?"

If you are not already familiar with the View system, you should read the next department as information technology is necessary to motivate and understand what a Composable is.

View Bureaucracy

In the context of the Android SDK (the libraries we use to brand user interfaces on this platform), a View is what we utilize to give construction and way to our applications.

Information technology is the most fundamental kind of building block or element of a given user interface (UI), and each of these building blocks volition contain the following kinds of information (among other things):

  • X and Y get-go and end positions which tell the computer where to draw the view on the device screen
  • Color and blastoff (transparency) values
  • Font data, text, symbols, and images
  • Behaviour based on events such as user interaction (clicks) or changes in the awarding's data (more on that later on)

It is important to understand that a View tin exist something like a button (commonly referred to as a "widget"), but information technology tin can also be a container of the whole screen, part of the screen, or for other child Views .

Such containers are commonly referred to as Layouts or Viewgroups depending on the context. And, while sharing most of the same kinds of information as a widget, they as well contain data near how to arrange and display other Views which are nested within them.

With that in mind, we become to the of import role of this review of the View arrangement: The View Hierarchy . For Web Developers, the View Hierarchy is essentially Android's version of the Document Object Model (DOM).

For Android Developers, you tin can think of the View Hierarchy as a virtual representation of all the Views which you defined either in XML files or programmatically in Java or Kotlin.

To illustrate this, allow's expect at such an XML file (at that place's no need to study it closely, just note the names). So, using a debugger/stepper tool, we will expect at what it looks like in the retentivity infinite of the Fragment which inflates this file:

fragment_hour_view.xml:

                <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/root_hour_view_fragment" xmlns:app="http://schemas.android.com/apk/res-auto" > <androidx.compose.ui.platform.ComposeView android:id="@+id/tlb_hour_view" //...  /> <com.wiseassblog.samsaradayplanner.ui.managehourview.HourToggleView android:id="@+id/vqht_one" //... /> <com.wiseassblog.samsaradayplanner.ui.managehourview.HourToggleView android:id="@+id/vqht_two" //... /> <com.wiseassblog.samsaradayplanner.ui.managehourview.HourToggleView android:id="@+id/vqht_three" //... /> <com.wiseassblog.samsaradayplanner.ui.managehourview.HourToggleView android:id="@+id/vqht_four" //... /> </androidx.constraintlayout.widget.ConstraintLayout>              

Memory Infinite of (Fragment)HourView.kt:

image-22
Image of a View Hierarchy

The debugger and stepper tools are some of my favourite ways to learn about what is going on under the hood of the lawmaking that I use from various libraries. Give it a attempt some time!

The purpose of showing you this XML file and what it turns into in a process (a process is merely a program that is running on a device), is to demonstrate how nested Views in an XML file translate into a nested View Hierarchy at runtime.

Hopefully, with a elementary merely concrete model of how the old arrangement works, we can compare it with the new one.

Are Composables Views?

This was i of the kickoff questions I asked when I started working with Etch, and the answer I accept arrived at is both yes and no .

Yes , in the sense that a Composable fulfills the same conceptual role as a View in the old system. A Composable tin exist a widget like a button, or a container such as a ConstraintLayout (it is worth noting that there is a Composable implementation of ConstraintLayout available).

No , in the sense that the UI is no longer represented virtually in a View Hierarchy (autonomously from situations involving interoperability). With that beingness said, compose does non use magic to about represent and keep runway of the UI. This means that it must have its ain thing which is conceptually similar to a View Hierarchy.

Allow u.s.a. take a very brief wait at this thing. Here, we have an Activity which uses the setContent {…} role to bind a Composable to itself:

ActiveGameActivity.kt:

                class ActiveGameActivity : AppCompatActivity(), ActiveGameContainer { private lateinit var logic: ActiveGameLogic override fun onCreate(savedInstanceState: Packet?) {     super.onCreate(savedInstanceState)     val viewModel = ActiveGameViewModel()     setContent {         ActiveGameScreen(             onEventHandler = {                 logic.onEvent(it)             },             viewModel         )     }     logic = buildActiveGameLogic(this, viewModel, applicationContext) } //… }              

ActiveGameScreen.kt:

                @Composable fun ActiveGameScreen(     onEventHandler: ((ActiveGameEvent) -> Unit),     viewModel: ActiveGameViewModel ) {     //...      GraphSudokuTheme {         Cavalcade(             Modifier                 .background(MaterialTheme.colors.primary)                 .fillMaxHeight()         ) {             ActiveGameToolbar(                 clickHandler = {                     onEventHandler.invoke(                         ActiveGameEvent.OnNewGameClicked                     )                 }             )              Box {               //content             }         }     } }              

In Etch, the View Bureaucracy is replaced with something that we tin can locate if nosotros dig really securely into the mWindow field of this Activity. Within that field is the conceptual replacement of the View Hierarchy: The Composer and its slotTable .

image-26

At this point, if you desire a detailed overview of the Composer and its slotTable, I must again propose that you read Leland'southward article (he goes into detail in part 2). At that place is more to the Compose Hierarchy than the Composer and its slotTable, but that should be sufficient to become us started.

In full general terms, Jetpack Compose uses what we might call its Etch Hierarchy (which is made of, and managed by things similar the Composer and its slotTable).

Once more, this is the same conceptual idea every bit the View hierarchy, a bunch of objects in memory space which collectively represent the UI, but it is implemented very differently.

There's an important difference, though, which is tricky to empathise technically, but like shooting fish in a barrel to sympathise in principle. This is the way in which Compose handles updates to the Compose Hierarchy: Recomposition .

Recomposition: How To Update Etch UI

For my ESL friends, the discussion Compose comes from the latin componere , which roughly ways "to put together." Someone who writes music is often called a "Composer," which can be thought of equally the one who puts together the notes coming from one or more instruments into a limerick (song).

Putting together implies that there are private pieces. It's of import to understand that almost any adept software developer makes at least some effort to break their code down into the smallest reasonable parts .

I mention reasonable , considering I think principles like DRY (Don't Repeat Yourself) should be followed merely to the extent that they solve more problems than they create.

At that place are many benefits to applying this concept, which is frequently called modularity, (or as I prefer, Separation of Concerns, or SOC). I am enlightened that some of you lot reading this might recall I am just copying what Leland said in his article, simply I take been talking about SOC as the Golden Principle Of Software Architecture for many years already.

Where this plays into Compose, is the same principle which nosotros see in the pop Javascript library React . When done properly, Compose will only "recompose" (redraw, re-render, update, any) the Composables (parts/elements of the UI) which need to be recomposed.

This is ENORMOUSLY important when it comes to the performance of an awarding. This is because redrawing the UI, whether in the quondam View organisation or in Compose, is costly for system resources.

In case you were not enlightened, the unabridged purpose of the old RecyclerView (which was the commencement matter I always made a tutorial on back in 2016!) was to use the ViewHolder pattern to a list of information. This avoided the demand to constantly inflate (make) new Views for each listing item.

My goal in this article was to focus mostly on the theory, every bit I volition be writing plenty of applied content over the adjacent few months. Notwithstanding, I volition finish the article off with a story from my direct experience, which will assistance you to further understand how recomposition works, and how to avoid doing it very poorly!

The Stopwatch Case

For my first full Compose application, I decided to build Sudoku. There are a number of reasons why, including the fact that I wanted a project which did non have an insanely complicated UI. I likewise wanted the chance to deep swoop into Graph DS and Algos, which are quite suitable for Sudoku puzzles.

One thing I wanted was a Stopwatch which would keep track of how long it took the user to complete a puzzle:

image-27
Graph Sudoku puzzle

Every bit is often the instance in my profession, I expected this timer to be much easier to add than it really was. I messed around with Android'southward Chronometer class every bit well as the Java Timer course, and both of them presented different simply still application-breaking problems.

Eventually I took a step back and realized that I was writing in Kotlin. So I gear up a Coroutine based timer in my presentation logic form (it concluded up making the well-nigh sense to put it there), which would update my viewmodel each 2d:

                Class ActiveGameLogic(…):…{ //… inline fun startCoroutineTimer(     delayMillis: Long = 0,     repeatMillis: Long = 1000,     crossinline action: () -> Unit of measurement ) = launch {     delay(delayMillis)     if (repeatMillis > 0) {         while (true) {             action()             delay(repeatMillis)         }     } else {         action()     } } private fun onStart() = launch {     gameRepo.getCurrentGame(     { puzzle, isComplete ->         viewModel.initializeBoardState(             puzzle,             isComplete     )         if (!isComplete) timerTracker = startCoroutineTimer {             viewModel.updateTimerState()         }     },{         container?.onNewGameClick()     }) } //… }              

The ViewModel (not from AAC – I write my own VMs. Merely Compose already has good interoperability with AAC VMs from what I tin meet.) exposed references to callback functions, which is what I would utilize to update my Composables:

                class ActiveGameViewModel {     //…     internal var subTimerState: ((Long) -> Unit)? = null     internal var timerState: Long = 0L     //…     internal fun updateTimerState(){         timerState++         subTimerState?.invoke(timerState)     } //… }              

At present comes the important part! We can trigger recomposition of the Compose Bureaucracy by using sure features of compose, such as the remember function:

                var timerState past remember {     mutableStateOf("") }              

If y'all must know, these features store the state of whatever you are remembering in the slotTable. In short, the word state here means the electric current "state" of the information, which starts out being just an empty String.

Here is where I screwed things upwards . I had pulled my simple timer composable into its own function (applied SOC), and I was passing in timerState as a parameter to that composable.

Even so, the to a higher place snippets were sitting in the parent composable of the timer, which was a container for the nigh complicated portion of the UI (a 9x9 Sudoku requires a large number of widgets):

                @Composable fun GameContent(     onEventHandler: (ActiveGameEvent) -> Unit of measurement,     viewModel: ActiveGameViewModel ) {     Surface(         Modifier             .wrapContentHeight()             .fillMaxWidth()     ) {         BoxWithConstraints(Modifier.background(MaterialTheme.colors.primary)) {             //…             ConstraintLayout {                 val (board, timer, diff, inputs) = createRefs()                 var isComplete by call back {                     mutableStateOf(false)                 }                 var timerState past call back {                     mutableStateOf("")                 }                 viewModel.subTimerState = {                     timerState = it.toTime()                 }                 viewModel.subIsCompleteState = { isComplete = information technology }             //…Sudoku board             //Timer                 Box(Modifier                     .wrapContentSize()                     .constrainAs(timer) {                         elevation.linkTo(board.bottom)                         beginning.linkTo(parent.showtime)                     }                     .padding(beginning = 16.dp))                 {                     TimerText(timerState)                 }             //…difficulty display             //…Input buttons             }         }     } } @Composable fun TimerText(timerState: String) {     Text(         text = timerState,         way = activeGameSubtitle.copy(color = MaterialTheme.colors.secondary)     ) }              

This was causing some considerable lag and unresponsiveness. By making heavy usage of the debugger, I was able to find out why. Because my timerState variable was created and updated within the parent Composable, information technology was triggering a recomposition of that entire portion of the UI. Every. Single. Tick.

After moving the appropriate lawmaking into the TimerText composable, things worked very smoothly:

                @Composable fun TimerText(viewModel: ActiveGameViewModel) {     var timerState past remember {         mutableStateOf("")     }      viewModel.subTimerState = {         timerState = it.toTime()     }      Text(         text = timerState,         style = activeGameSubtitle.re-create(colour = MaterialTheme.colors.secondary)     ) }              

Hopefully I have given you a working understanding of recomposition and one of the biggest ways to do information technology incorrectly.

Avoiding unnecessary recompositions is incredibly of import for operation. And so far it seems that applying SOC rigorously, even to the point of keeping remember state in divide composables, should become standard do.

Resources & Support

If y'all liked this article, delight share it on social media and cheque out my other articles on freeCodeCamp hither. I also have a YouTube channel with hundreds of tutorials, and am an agile author on various platforms.

You tin observe me on Instagram here and on Twitter here.

Also, I desire to point out the single resources I used to become started with Jetpack Compose: Working code samples from skilful developers.



Learn to lawmaking for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs equally developers. Become started

barneslonts1937.blogspot.com

Source: https://www.freecodecamp.org/news/jetpack-compose-beginner-tutorial-composables-recomposition/

0 Response to "How to Read All the Text From a File and Close It C++"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel