Computer >> 컴퓨터 >  >> 체계 >> Android

Kotlin 및 Jetpack Compose로 Android 앱 만들기

Jetpack Compose는 기본 UI를 구축하기 위한 Android의 최신 툴킷입니다. Android에서 UI 개발을 간소화하고 가속화합니다.

Kotlin 및 Jetpack Compose를 사용하여 Sudoku Android 앱을 만드는 방법을 알려주는 freeCodeCamp.org YouTube 채널에 강의를 공개했습니다.

그 과정에서 그래프 데이터 구조와 알고리즘에 대해서도 배우게 됩니다.

Ryan M. Kay가 이 과정을 개발했습니다. Ryan은 경험이 풍부한 개발자이자 교사입니다.

이 과정에서 다루는 섹션은 다음과 같습니다.

  • 앱 디자인 접근 방식:타사 라이브러리 미니멀리즘 및 MV-무엇이든 아키텍처
  • 도메인 패키지:저장소 패턴, 열거형, 데이터 클래스, 봉인된 클래스, 해시 코드, 인터페이스
  • 공통 패키지:확장 함수 및 변수, OCP(개방형 원리), 추상 클래스, 싱글톤
  • 지속성(저장소) 패키지:Java 파일 시스템 저장소가 포함된 클린 아키텍처 백엔드, Jetpack Proto Datastore
  • UI 패키지:Jetpack Compose UI 기본, 스타일, 타이포그래피, 밝고 어두운 테마
  • UI 구성 요소 패키지:수정자, 재사용 가능한 도구 모음 및 로딩 화면
  • UI 활성 게임 기능 패키지:프레젠테이션 논리 및 ViewModel w/ 코루틴, Kotlin 함수 유형
  • UI 활성 게임 기능 패키지:Jetpack Compose UI 및 활동 컨테이너가 포함된 스도쿠 게임
  • Computation Logic 패키지:n-size *square* Sudokus용 Graph DS 및 Algos의 개요, 설계 및 테스트

아래 또는 freeCodeCamp.org YouTube 채널에서 전체 과정을 시청하십시오(3.5시간 시청).

대본

(자동 생성)

이 과정에서는 jetpack compose UI 라이브러리를 사용하여 Android 앱을 만드는 방법을 배웁니다.

그 과정에서 그래프 알고리즘과 데이터 구조에 대해 배우게 됩니다.

Ryan M. Kay가 이 과정을 가르칩니다.

그는 경험이 풍부한 개발자이자 강사입니다.

무슨 일이야? 저는 여기 Ryan입니다. 그래프 스도쿠 애플리케이션에 대한 튜토리얼 시리즈에 오신 것을 환영합니다.

이것은 주로 그래프 데이터 구조와 알고리즘에 대한 이해를 개선하기 위해 작성한 애플리케이션이며 Android jetpack compose의 새로운 UI 라이브러리입니다.

시리즈의 이 부분에서 나는 시리즈의 주요 목표와 주제를 개관하고 당신을 놀라게 할 수 있는 몇 가지 디자인 결정에 대해 논의할 것입니다.

프로젝트 소스 코드의 공개 버전을 최신 상태로 유지하도록 노력하겠습니다.

더 이상 사용되지 않거나 작동이 중지되는 경우 해당 소스 코드를 확인하는 것은 귀하의 책임입니다.

이 시리즈의 형식은 스타일에 따른 코드로, 가장 좋은 학습 방법은 내가 설명하는 대로 코드를 작성하는 것입니다.

고급 개발자의 경우 전체 소스를 직접 학습할 수 있지만 비디오를 보고 지식의 허점을 해결할 수 있습니다.

저는 kotlin 언어의 상당히 고급 기능과 소프트웨어 아키텍처의 시대를 초월한 원칙을 사용하므로 한두 가지를 배울 수 있습니다.

초보자의 경우 코드에서 저와 함께 자신의 속도로 따라가는 것이 매우 중요합니다.

처음에는 발전하고 있다고 느끼지 않을 수 있지만 아직 작성 중인 내용을 이해하지 못하더라도 코드 작성 기술을 연습하게 될 것임을 이해하십시오.

또한 작성, 읽기, 수정, 개선 및 테스트하기 쉬운 코드를 작성하는 방법을 비밀리에 가르칠 것입니다.

그러나 소프트웨어 설계의 시대를 초월한 원칙을 외우라고 요구하는 대신 이 응용 프로그램을 구축하면서 실제로 배우고 사용하게 될 것입니다.

이 튜토리얼에서는 깔끔한 UI 아키텍처와 kotlin 언어 기능을 구성하는 제트팩의 그래프 데이터 구조와 알고리즘을 보여주는 네 가지 일반적인 주제가 있습니다.

우리는 방향이 있는 컬러 그래프와 해결되지 않은 n 크기의 스도쿠 퍼즐을 생성하기 위한 알고리즘 작성 실험에 대한 주제를 탐구할 것입니다.

우리는 Jetpack compose를 사용하여 전체 사용자 인터페이스를 구축할 것입니다. 이를 통해 완전히 kotlin에서 UI를 생성할 수 있습니다.

XML 보기 및 스타일과 반대입니다.

견고하고 깔끔한 아키텍처에서 일반적으로 설명되는 원칙을 사용하여 간단한 앱을 연결하는 방법을 보여 드리겠습니다.

하지만 저는 이러한 주제를 저만의 방식으로 가르치므로 전문 용어나 과도한 엔지니어링을 기대하지 마십시오.

또한 이 아름다운 프로그래밍 언어의 기본 기능과 고급 기능을 언제 어떻게 사용하는지 보여드리겠습니다.

비디오의 이 부분은 중급 및 고급 개발자를 위한 것입니다.

이 디자인 결정을 이해하는 것은 튜토리얼을 완료하는 데 필요하지 않습니다.

이 튜토리얼 전반에 걸쳐 compose 및 proto 데이터 저장소를 제외하고는 Android jetpack의 라이브러리를 거의 사용하지 않는다는 사실을 알게 될 것입니다. 사실, 일반적으로 kotlin 및 Java 표준 라이브러리와 Android SDK에 의존하는 타사 라이브러리는 거의 없습니다. 라이브러리의 사용 중단 및 변경 사항에 대한 내성이 높아집니다.

이는 Android SDK 및 표준 라이브러리가 Android Jetpack과 같은 타사 라이브러리보다 덜 자주 변경되는 경향이 있기 때문입니다.

또한 jetpack viewmodel, jetpack, 탐색 또는 도움말과 같은 라이브러리가 처리할 수 있는 일부 항목은 우리가 직접 작성해야 함을 의미합니다.

나는 그것이 실제로 마음에 들지만 당신은 다른 가치 체계를 가질 수 있습니다.

여기서 제 목표는 관심이 있는 경우 이러한 도구를 배우지 못하도록 하는 것이 아닙니다.

즉, 이와 같은 작은 앱에서 뷰 모델 탐색 또는 종속성 주입 코드 없이 자신만의 뷰 모델 탐색 또는 종속성 주입 코드를 작성하는 것이 얼마나 쉬운지 놀랄 것입니다.

이 응용 프로그램은 아키텍처가 무엇이든 Model View를 사용합니다. 이는 다른 사람의 스타일을 따르지 않는다는 제 방식입니다.

수년 동안 이 주제를 연구한 결과, 좋은 소프트웨어 디자인의 원칙에 대한 이해의 프로젝트 요구 사항이 내 아키텍처의 지침이 되도록 했습니다.

이 경우 작성은 MVVM 기반 접근 방식을 위해 만들어졌지만 특정 이유로 프레젠테이션 로직 클래스를 추가했습니다.

이러한 이유를 수동적 견해 또는 겸손한 대상이라고 합니다.

보기나 보기 모델이 각 화면의 제어 흐름을 관리하도록 하는 대신 해당 논리를 별도의 클래스로 가져왔습니다.

이 클래스는 타사 종속성이 없기 때문에 작성 및 테스트가 매우 쉽습니다.

그리고 내 뷰 모델이 추한 God 객체가 되는 것을 방지합니다.

한 번 시도해 보세요.

소프트웨어 아키텍처의 가장 중요한 원칙인 관심사 분리를 적용하여 이 아키텍처를 설계했습니다.

여기까지가 시리즈의 이 부분입니다.

이제 코딩을 시작합니다.

도메인 패키지는 데이터 클래스, 상수 및 프로그램이 가상으로 나타내야 하는 충분과 같은 가장 일반적인 정보의 두 가지를 나타냅니다.

또한 이 프로그램이 수행해야 하는 가장 일반적인 작업, 즉 프로그램이 함수와 인터페이스를 사용하여 나타내는 것입니다.

본질적으로 이는 내가 평가하는 모든 새 프로그램의 기초이며 반복 가능한 프로세스를 사용하여 도메인 패키지 또는 모듈을 디자인합니다.

해당 프로세스에 대한 명확하고 간단한 소개가 필요합니다.

내 채널에서 정보 시스템 및 응용 프로그램을 설계하는 방법에 대한 비디오를 확인하십시오.

그 비디오는 내가 이집트의 일부 소프트웨어 엔지니어에게 그 특정 주제에 대해 한 연설을 녹음한 것입니다.

어쨌든 이 패키지에 있는 대부분의 코드는 단순하지만 지금 소개할 디자인 패턴이 포함되어 있습니다.

이 패키지에는 저장소 디자인 패턴을 사용하는 데 사용되는 여러 인터페이스가 포함되어 있습니다.

이 패턴은 파사드 패턴이라고도 합니다.

그리고 패턴의 일반적인 목표는 기술적인 정의보다 간단합니다.

파사드 또는 리포지토리 패턴의 기술적 정의는 하위 시스템의 세부 사항을 숨기는 것입니다. 이 경우에는 추상화 뒤에 있는 데이터 저장 메커니즘, 이 경우에는 인터페이스입니다.

실용적인 예를 살펴보겠습니다.

이 정의를 이해하기 위해 프레젠테이션 논리 클래스는 인터페이스를 구현하는 클래스 대신 이러한 저장소 인터페이스에 대한 참조를 보유합니다.

이는 프레젠테이션 로직 클래스에 몇 가지 이점을 제공합니다.

컴파일러 오류를 일으키지 않고 서로 독립적으로 빌드할 수 있으며 프레젠테이션 로직 클래스 내에서 코드를 변경할 필요 없이 인터페이스의 가짜 구현으로 테스트할 수 있습니다.

또한 파일 저장소에서 회의실 데이터베이스로 전환하는 것과 같이 인터페이스의 다른 구현을 사용하기로 결정한 경우 프레젠테이션 논리 클래스를 변경하지 않고도 이를 수행할 수 있습니다.

이러한 이점은 느슨하게 결합된 소프트웨어 시스템을 구축한 결과입니다.

그리고 저장소 또는 파사드 패턴은 느슨한 결합을 촉진하는 쉬운 방법입니다.

사실 인터페이스는 일반적으로 느슨한 결합을 촉진하는 경향이 있습니다.

이제 모든 곳에서 이 패턴을 사용할 필요를 느끼지 마십시오.

좋은 일반 규칙은 중요한 아키텍처 경계에서 사용하는 것입니다.

이 경우 이 애플리케이션의 프런트 엔드와 백 엔드 사이의 경계로 사용하고 있습니다.

시작하려면 도메인 패키지를 마우스 오른쪽 버튼으로 클릭하고 새 kotlin 파일로 이동하여 난이도라는 파일을 만드세요.

그리고 그것은 열거형 클래스가 될 것입니다.

kotlin의 enum 클래스, Java 및 기타 다양한 언어는 제한된 값 집합을 만드는 데 유용합니다.

나중에 살펴보겠지만 kotlin에서 봉인된 클래스를 사용하여 제한된 유형 집합을 만들 수 있습니다.

어쨌든 제한된 값 집합을 만드는 것 외에 주요 이점은 열거형이 프로그램의 가독성을 크게 향상시킬 수 있다는 것입니다.

잠시 후 살펴보겠지만 열거 항목을 추가해 보겠습니다.

분명히 이 열거형은 주어진 스도쿠 퍼즐의 난이도를 나타냅니다.

그러나 계속 진행하기 전에 한 가지를 더 추가해야 합니다. 실제로 알고리즘의 각 항목에 대해 일부 값을 사용하여 기본적으로 스도쿠 퍼즐의 난이도를 결정합니다.

따라서 kotlin의 enum에 값을 추가하려면 속성 또는 일부 속성을 부여해야 합니다.

보시다시피, 우리의 항목은 이제 읽혀졌으므로 분명히 몇 가지 복식을 제공해야 합니다.

이것이 우리가 여기서 해야 할 모든 것입니다.

메인 패키지를 우클릭하여 New kotlin file for class로 이동합니다.

그리고 settings라는 데이터 클래스를 만들 것입니다.

settings는 우리의 첫 번째 데이터 모델입니다. 저는 이것을 평범한 오래된 kotlin 객체라고 부르고 싶습니다.

그리고 잠시 후 살펴보겠지만 여기에는 난이도와 스도쿠 퍼즐 크기의 경계가 모두 포함됩니다.

따라서 4x4 스도쿠 퍼즐의 경계는 4이고, 9x9의 경계는 9입니다.

data 키워드는 class 키워드 앞에 위치할 때 기본적으로 equals hash code나 copy와 같은 몇 가지 도우미 메서드를 추가하거나 생성합니다.

우리는 나중에 이 수업이 아닐 수도 있지만 그 중 일부와 다른 수업에서 복사를 확실히 사용할 것입니다.

특정 시점에서 생성된 해시 코드 기능도 사용할 것입니다.

어쨌든 이 클래스는 정말 간단한 클래스이므로 두 개의 속성을 추가하기만 하면 됩니다.

그게 다야.

도메인 패키지를 마우스 오른쪽 버튼으로 클릭하고 새 kotlin 클래스 또는 파일로 이동합니다.

그리고 이번에는 사용자 통계라는 클래스를 만들 것입니다.

그리고 그것은 데이터 클래스가 될 것입니다.

이제 이 클래스의 목적은 특정 난이도나 크기의 스도쿠 퍼즐을 풀기 위한 사용자의 최단 슬래시 최고의 시간을 나타내는 것입니다.

따라서 기본적으로 거의 동일한 속성을 모두 추가할 것입니다.

이제 IntelliJ IDEA 또는 Android Studio에서 할 수 있는 한 가지는 그곳을 클릭한 다음 Ctrl D를 몇 번이고 눌러도 새 줄에 복사됩니다.

이것이 이 수업의 기본입니다.

이제 여기서 long을 사용하는 이유가 궁금할 것입니다. 실제로 사용자가 특정 게임을 완료하는 데 걸리는 시간을 밀리초 단위로 저장하고 있습니다.

이것이 우리가 긴 정수 값을 원하는 이유입니다.

다시 도메인 패키지를 마우스 오른쪽 버튼으로 클릭하고 New kotlin filer class로 이동하면 Sudoku note라는 데이터 클래스가 됩니다.

이제 데이터 모델이 좀 더 복잡해지고 흥미로워지기 시작했습니다.

그래서 여기서 제가 하고 있는 것은 그래프 데이터 구조에서 개별 노드를 나타내는 것입니다. 나중에 그래프 데이터 구조에 대한 전용 튜토리얼 부분에 도달하면 그래프 데이터 구조에 대해 더 많이 이야기할 것입니다.

하지만 아이디어를 제공하기 위해 실제로 유색 그래프를 만들 것입니다.

여기서 주목해야 할 중요한 점은 이 특별한 경우에 이 색상이라는 용어는 실제로 숫자를 의미하며 일종의 노드에서 연관시키는 값일 뿐입니다.

그리고 다시 미리 미리보기를 제공하기 위해 그래프 데이터 구조라고 하면 네트워크 데이터 구조가 더 나은 이름이 될 것입니다. 기본적으로 네트워크 데이터 구조이기 때문입니다.

본질적으로 노드 사이의 선과 같은 노드와 에지의 모음입니다.

어쨌든, 우리 데이터 구조의 이 특정 노드 구조는 1에서 9 또는 1에서 4 사이의 정수인 색상 또는 값을 가질 것입니다. 또한 00을 포함하면 빈 스도쿠 타일과 비슷하지만 그것이 더 우려됩니다. 프런트 엔드.

이 메모에는 X 및 Y 좌표도 포함되므로 왼쪽 상단은 x 0 y 0이 되고 오른쪽 하단은 x 8, y 8이 되며 0 기반 인덱싱을 사용할 것입니다.

따라서 x 1에서 x 9까지 시작하는 대신 기본적으로 1을 뺍니다.

서문은 여기까지입니다. 코드 작성을 시작해 보겠습니다.

따라서 x 및 y 값부터 시작하겠습니다.

다음으로 실행 과정에서 변경될 수 있으므로 변수가 될 색상을 추가합니다.

그런 다음 읽기 전용이라는 부울을 추가하고 작성한 후 이것이 무엇인지 설명하겠습니다.

이제 여기에서 읽기 전용 부울의 목적은 매우 간단합니다.

우리가 본질적으로 스도쿠 퍼즐을 생성한 다음 해결하지 못할 때, 이는 새로운 스도쿠 퍼즐을 만든 다음 특정 수의 단서를 제거하여 게임을 실제로 플레이할 수 있고 재미있게 만드는 또 다른 방법입니다.

스도쿠 보드나 스도쿠 그래프 데이터 구조에 있는 숫자 중 일부는 사용자가 스스로를 변경할 수 없다는 주어진 단서와 같은 숫자만 읽을 수 있습니다.

나중에 살펴보겠지만

읽기 전용 스도쿠 노드 또는 타일을 사용자가 편집할 수 있는 것과 다르게 그리기 때문에 이는 사용자 인터페이스에도 영향을 미칩니다.

자, 아직 완료되지 않았습니다. 앞에서 설명한 것처럼 data class 키워드가 제공한 해시 코드 함수를 재정의해야 하며 해시 코드를 가져오는 함수도 추가해야 합니다.

알겠습니다. 해시 코드는 기본 구현을 갖게 되며 이는 여기에서 제공하는 다양한 속성 값을 기반으로 하므로 실제로는 다른 작업을 수행할 것입니다.

그래서 우리는 get hash를 입력할 것입니다.

그리고 이것은 실제로 우리가 만들 함수이기도 합니다. 여기에 x와 y에 대해 두 개의 매개변수를 추가할 것입니다.

자, 이제 get hash 함수를 추가할 것입니다. 이것은 최상위 수준이 될 것입니다. 즉, Sudoku 노드 클래스의 대괄호 외부에 위치합니다.

좋습니다. 이 기능을 구현한 다음 여기서 무엇을 하는지 설명하겠습니다.

알겠습니다. 해시 코드 또는 해시 값이 정확히 무엇인지 설명하는 것으로 시작하겠습니다.

따라서 본질적으로 일종의 생성된 키 또는 일종의 알고리즘을 기반으로 하는 고유 식별자입니다.

이 경우 매우 간단한 알고리즘이 있습니다. x 값에 100을 곱하기만 하면 됩니다.

그리고 y 값은 그대로 둡니다.

그리고 기본적으로 이 두 값을 정수로 결합합니다.

이제 x에 100을 곱한 이유는 9x9 스도쿠 퍼즐에서 그렇게 하지 않으면 X와 Y 값이 기술적으로 다르더라도 결과 해시 코드가 여러 노드에 대해 고유하지 않습니다.

간단히 말해서, 스도쿠 퍼즐의 모든 개별 타일에 고유한 해시 코드를 만들기 위해 100을 곱합니다.

해시 코드를 사용하는 이유는 일반적으로 매우 간단하게 유지하려고 합니다.

기본적으로 그래프의 각 노드를 연결된 해시 맵에 저장합니다.

따라서 해시 값은 해당 해시 맵의 키를 나타냅니다.

해시 맵에는 키 값 쌍이 있습니다. 모르는 경우를 대비하여 잠시 후에 확인하겠습니다.

그러나 이것은 사용자 인터페이스도 X 및 Y 좌표 스타일과 같은 종류를 나타내기 때문에 매우 유용한 것으로 판명되었습니다.

그러니 제 말을 믿으세요.

해시 코드는 많은 수의 요소가 있고 모든 개별 요소에 대한 참조를 유지할 필요가 없는 상황에서 매우 편리합니다.

대신 해시 코드를 가져와 참조를 검색할 수 있습니다.

아, 그리고 가기 전에 여기에 한 가지를 더 추가해야 합니다. 이 작업을 직렬화 가능하게 구현해야 합니다.

이제 본질적으로 이것이 하는 일은 스도쿠 노드와 전체 퍼즐을 파일로 읽고 쓸 수 있도록 하는 것입니다.

한 번에 하나의 퍼즐만 저장할 것이기 때문에 데이터베이스와 같은 것을 사용하고 싶지 않았습니다. 본질적으로.

자, 이 특정 패키지에서 다시 생성할 최종 데이터 모델이 하나 있습니다. New kotlin file our class를 마우스 오른쪽 버튼으로 클릭합니다. 이 모델을 스도쿠 퍼즐이라고 부를 것입니다.

그리고 다시 데이터 클래스가 됩니다.

내가 좋아하는 데이터 모델을 생각하는 좋은 방법은 데이터 모델이 실제 세계 개체의 가상 표현이라는 것입니다. 이 경우에는 스도쿠 퍼즐입니다.

처음에 이 수업을 디자인한 방법은 스도쿠 퍼즐을 구성하는 요소에 대해 비판적인 질문을 하는 것이었습니다.

경계와 같은 것은 행 또는 열당 4개의 타일이 있거나 예를 들어 9개의 타일이 있는 경우 어려움이 있습니다.

그리고 가장 중요한 것은 그래프 데이터 구조 자체가 있다는 것입니다.

사용자가 특정 퍼즐을 푸는 데 걸린 시간도 있습니다.

이제 이러한 속성을 추가한 다음 나중에 설명해야 하는 속성에 대해 설명하겠습니다.

또한 잊어버리기 전에 직렬화 가능한 구현을 여기에 추가하겠습니다.

알겠습니다. 새 스도쿠 빌드가 무엇인지 궁금하실 것입니다.

그래서 우리가 할 일은 실제로 주어진 크기를 기반으로 새로운 스도쿠 퍼즐을 만들고 생성하는 데 필요한 모든 다른 알고리즘을 형성하는 대규모 일련의 최상위 함수를 호출하는 것입니다. , 이것이 경계가 나타내는 것과 주어진 어려움입니다.

또한 링크드 리스트로 가득 찬 링크드 해시 맵이 어떻게 되는지 궁금하다면, 그것은 일종의 인접 리스트를 표현하는 방식입니다.

다시 말하지만, 그래프 데이터 구조 및 이를 표현할 수 있는 다양한 방법에 대한 세부 사항, 또는 적어도 나중에 해당 특정 패키지 및 주제에 도달했을 때 이 특정 애플리케이션에서 데이터 구조를 표현하는 방법에 대해 자세히 설명하겠습니다.

그러나 당분간 이것이 가상 스도쿠 퍼즐을 나타낸다는 것을 이해하기 위해 마지막으로 할 일은 그래프 자체를 파악하는 방법을 좀 더 명확하고 읽기 쉽게 만드는 작은 방법을 추가하는 것입니다. 적어도 제 생각에는.

그리고 우리는 단일 표현식 구문을 사용할 것입니다.

그래서 저는 equals graph를 입력하겠습니다.

I 게임 저장소라는 새 인터페이스를 만들어 보겠습니다.

저는 인터페이스 앞에 대문자 I를 넣는 이 명명 규칙을 사용하는 것을 좋아합니다.

그리고 나중에 보게 되겠지만, 지속성 패키지에서 I MPL의 접미사를 추가할 것입니다. 이는 이 인터페이스를 구현하는 클래스에 대한 구현을 의미합니다.

중소 규모의 애플리케이션을 설계할 때 할 수 있는 한 가지는 실제로 저장소 인터페이스의 기능을 개념적으로 생각할 수 있다는 것입니다.

유스 케이스 자체로서, 우리가 여기서 작성하려는 것들은 게임 업데이트 게임 업데이트 노드 저장과 같이 호출될 것입니다. 이는 유스 케이스 유형 애플리케이션 디자인에서 사용자 스토리처럼 하는 경우 매우 유사합니다.

그래서 그냥 거기에 넣고 싶었습니다.

여러 다른 데이터 소스와 리포지토리를 더 많이 조정해야 하는 더 복잡한 응용 프로그램에서는 Martin Fowler 또는 Robert Martin, Bob 삼촌 사이에 일반적으로 이야기되는 인터랙터 또는 사용 사례가 있을 것입니다.

그러나 이 특별한 경우, 일반적으로 말해서 클래스 자체로서의 사용 사례는 더 단순한 응용 프로그램에서 일반적으로 불필요한 추가 추상화 계층입니다.

여기에서 우리는 발표자와 함께 가거나 모델을 보거나 무엇이든 저장소와 직접 대화할 것입니다.

그리고 이것은 이 크기의 애플리케이션을 위한 충분한 추상화입니다.

이제 인터페이스가 작동하는 방식은 클래스와 매우 유사하다는 것입니다. 잠시 후 실제로 작성할 기능을 구현하거나 본문을 제공하는 것이 허용되지 않습니다. 일반적으로 추상 함수 또는 함수 스텁이라고 하는 것

이제 여기에 두 가지 중요한 사항이 있습니다.

첫째, suspend 키워드가 거기에 적용됩니다. 왜냐하면 이러한 함수는 이 특정 인터페이스를 참조할 논리 클래스 또는 프리젠터에 존재하는 공동 루틴 범위에서 실제로 호출되기 때문입니다.

지금으로서는 동시성을 설정하기 위해 해야 할 일은 이것이 전부입니다.

이제 익숙하지 않은 경우를 대비하여 여기서 사용하고 있는 것은 함수 유형이라고 하는 것입니다.

그래서 우리가 할 일은 실제로 논리 클래스에 존재하는 두 함수에 대한 참조를 전달하는 것입니다. 이 함수는 프레젠테이션 논리가 해당 함수를 전달할 것입니다.

그런 다음 저장소 구현에서 이 특정 인터페이스를 구현하는 것들이 성공적인 결과든 실패든 일종의 결과로 콜백하는 방법입니다.

이제 당신은 왜 우리에게 단위가 있고 이 특별한 경우에 그 화살표가 의미하는 단위를 반환하는지 궁금할 것입니다. 이것은 kotlin 컴파일러가 우리가 무엇을 하라고 말하는지 정확히 이해하기 위해 우리가 해야 할 일입니다.

따라서 이것은 void를 전달하거나 기본적으로 이 특정 함수에 아무 것도 전달하지 않은 다음 해당 특정 함수에서 아무 것도 반환하지 않는 것과 같습니다.

그러나 기본적으로 이 함수가 호출될 때 응용 프로그램을 성공적으로 재개하려는 RX Java에 대한 경험이 있는 경우 oncomplete와 같은 신호를 보낼 것입니다.

그러나 이 특정 함수는 실제로 아무 것도 반환할 필요가 없습니다.

나중에 on success 함수 유형을 통해 실제로 값을 반환해야 하는 경우에 대한 몇 가지 예를 볼 수 있습니다.

다시 말하지만, 게임을 저장하는 것과 게임을 업데이트하는 것의 차이점이 무엇인지 궁금할 것입니다. 음, 본질적으로 업데이트 게임 기능에서 우리는 경과 시간을 포함하는 전체 스도쿠 퍼즐을 전체적으로 작성하려고 합니다. 그러나 우리가 정말로 해야 하는 모든 상황이 단순히 게임의 경과 시간을 업데이트하는 것뿐인 경우도 있습니다. , 예를 들어 사용자가 애플리케이션에서 다른 곳으로 이동할 때.

그래서 제가 여기서 하는 일은 사용자의 관점에서 달성하고자 하는 것에 따라 일종의 특수 기능을 만드는 것입니다.

이제 이러한 특정 함수 유형에서 값을 실제로 반환하려는 경우를 보여드리겠습니다.

자, 성공을 위해 여기서 우리가 효과적으로 말하고 있는 것은 이 특정 함수가 이 특정 일시 중단 함수의 구현에서 호출될 때 분명히 true 또는 false인 부울 값의 일종으로 호출되어야 한다는 것입니다.

이제 기본적으로 여기서 우리가 하는 일은 사용자가 스도쿠 퍼즐에서 단일 노드나 타일을 업데이트할 때 퍼즐의 마지막 타일이 될 가능성이 있다는 것입니다.

그리고 그 특정한 경우에, 퍼즐이 정확하고 사용자가 최종 타일을 입력했다고 가정하면 게인이 완료되었다는 신호가 됩니다.

그래서 여기에서 약간 혼란스러울 수 있습니다.

하지만 성공했다고 해서 게임 자체가 완료된 것은 아닙니다.

그래서 제가 거기에서 차별화하고 있습니다.

자, 이제 이 특별한 경우에 사용자가 활성 게임으로 돌아올 때 현재 게임을 가져오기를 원합니다.

그리고 실제로 사용자가 게임을 완료하고 애플리케이션에서 다른 곳으로 이동한 다음 애플리케이션을 다시 시작하는 경우가 있습니다.

그래서 우리는 여전히 완전한 플래그를 전달하고 있습니다.

여기서는 분명히 설정 개체를 반환할 것입니다.

다른 인터페이스를 만들어 봅시다.

그리고 그것은 I gain, 데이터 저장이라고 부를 것입니다.

그리고 그것은 분명히 인터페이스입니다.

이제 인터페이스 자체를 작성하기 전에 약간 다른 작업을 수행하겠습니다.

결과 래퍼를 만들거나 기능적 프로그래머의 광고에서 영감을 얻었다고 가정해 보겠습니다. 하지만 기능적 프로그래머가 어떻게 생각하고 이야기하는지 아무도 신경 쓰지 않습니다.

Seal 클래스는 내가 정말 좋아하는 kotlin 프로그래밍 언어의 간단한 기능 중 하나입니다.

제한된 유형의 집합을 만들 수 있으며 이러한 유형에는 특정 값이 포함될 수 있습니다.

그리고 기본적으로 이것이 하는 일은 그리고 잠시 후에 보게 되겠지만 I 게임 데이터 저장소의 특정 기능에서 객체를 반환할 수 있게 해줍니다.

그리고 이 특정 개체는 여러 다른 상태를 나타낼 수 있습니다.

이전에 AI 게임 저장소에서 보여드린 것처럼 여기서는 오류 상태와 성공 상태를 두 개의 개별 함수 참조로 나타냅니다.

이 예에서는 단일 개체를 통해 두 상태를 모두 나타낼 것입니다.

이제 마지막으로 한 가지 요점으로 넘어가기 전에 예를 들어 성공 사례만 나타내고자 하는 상황이 있는 경우 onsuccess에서 유닛을 반환하는 것과 동일하므로 실제로 다음을 수행할 수 있습니다. 개체를 사용하여 완료 시 개체와 같이 말할 수 있습니다.

하지만 이 애플리케이션에서는 실제로 그렇게 하지 않습니다.

따라서 추가할 필요가 없습니다.

이제 인터페이스를 마치겠습니다.

I 설정 저장소라는 다른 인터페이스를 만듭니다.

이제 여기에서도 결과 래퍼를 사용할 것입니다.

그래서 실제로 이것을 복사하여 붙여넣겠습니다.

그리고 몇 가지 이름만 변경하겠습니다.

자, 이제 인터페이스를 작성할 수 있습니다.

이 패키지에 사용할 인터페이스가 하나 더 있습니다.

이것을 리포지토리로 철자할 수 있다면 이것을 파이 통계라고 부를 것이고, 분명히 인터페이스가 될 것입니다.

이제 마지막 요점은 업데이트되는 통계가 레코드인지 여부, 즉 스도쿠 퍼즐의 특정 경계 또는 크기에 대해 가능한 가장 짧은 완료 시간인지 여부에 따라 기록이 실제로 사용자 인터페이스의 무언가에 영향을 미칠 것이라는 점입니다. 특별한 어려움.

공통 패키지에는 다양한 클래스 및 기능에서 재사용되는 코드가 포함되어 있습니다.

튜토리얼의 이 부분에서는 지능적이고 효율적인 방식으로 코드를 공유하도록 설계된 다양한 kotlin 언어 기능에 대해 알아봅니다.

다루는 주제에는 확장 기능 및 문제가 포함됩니다. 이러한 추상 클래스, 개방형 폐쇄 원칙, 객체, 싱글톤 및 공동 루틴 디스패처.

코드를 작성하기 전에 개방형 폐쇄 원칙에 대해 이야기합시다.

OCP는 상대적으로 혼란스러운 개념이지만, 나중에 설명할 나 자신의 구두 정의를 제공하기 위해 최대한 명확하게 설명하려고 노력할 것입니다.

변경될 것으로 예상되는 일반적으로 재사용되는 모든 소프트웨어 엔터티에는 고정된 공용 인터페이스와 구현 변경 방법이 있어야 합니다.

그 특정 정의를 이해하기 위해 풀어야 할 몇 가지 사항이 있습니다.

첫째, 소프트웨어 개체라고 하면 일반적으로 클래스나 함수에 대해 이야기하는 것이지만 몇 가지 다른 것일 수도 있습니다.

그럼 공용 인터페이스가 무엇을 의미하는지, 그리고 일반적으로 재사용되는 경우 수정되어야 한다고 주장하는 이유를 살펴보겠습니다.

공개 인터페이스란 Java 또는 kotlin 인터페이스를 구체적으로 말하는 것이 아니라 공개적으로 표시되는 클래스 또는 함수 측면을 의미합니다.

Android 튜토리얼이므로 액티비티 클래스를 예로 들어보겠습니다.

활동은 일반적으로 재사용되고 시간이 지남에 따라 변경될 것으로 예상되는 내 요구 사항에 맞습니다.

따라서 OCP에 대해 생각하기에 완벽한 사례입니다.

활동의 모든 하위 클래스에는 공개 인터페이스의 일부인 onCreate 함수가 포함되어야 하며 이를 참조하는 클래스에서 사용할 수 있습니다.

이 공개 인터페이스가 변경되지 않기를 바라는 이유는 매우 간단합니다.

Android 플랫폼 개발자가 갑자기 모든 수명 주기 기능에서 저장된 인스턴스, 상태 번들을 사용 중단하고 제거하기로 결정했다고 가정해 보겠습니다.

이 공개 인터페이스는 이 플랫폼 업데이트와 관련된 거의 모든 Android 프로그램에서 사용되기 때문에 모든 사람의 코드가 손상될 수 있습니다.

내가 구체적으로 의미하는 바는 이 매개변수를 제거하지 않은 모든 코드 기반의 모든 활동 하위 클래스는 컴파일할 수 없다는 것입니다.

이것이 내가 활동과 같이 일반적으로 재사용되는 소프트웨어 엔티티에 대해 구체적으로 이야기하는 이유와 공개 인터페이스가 가능한 한 적게 변경되는 것이 중요한 이유입니다.

고정된 공개 인터페이스가 정말 중요한 이유를 확인했기 때문입니다.

다음 질문은 간단합니다.

그런 다음 공개 인터페이스 구현을 변경하기 위한 메커니즘이나 방법을 제공하려면 어떻게 해야 합니까? kotlin은 이 문제를 해결할 수 있는 다양한 옵션을 제공합니다.

그것들을 모두 구두로 설명하는 대신 코드에서 사용하는 방법을 가르쳐 드리겠습니다.

이 애플리케이션을 빌드할 때 공통 패키지를 마우스 오른쪽 버튼으로 클릭하고 새 kotlin 파일 또는 클래스로 이동합니다.

그리고 이것은 실제로 여기에서 옵션을 제공하지 않는 추상 클래스가 될 것입니다.

그래서 우리가 할 일은 기본 로직을 입력하고 추상 키워드를 추가하는 것입니다.

불행히도 나는 평범한 오래된 상속에서 추상 클래스와 인터페이스의 차이점을 설명할 시간이 없습니다.

이 특정 과정에서 이것은 제가 다른 비디오 과정에서 매우 명확하게 설명하고 설명하는 것입니다.

하지만 여기서 인터페이스 대신 추상 클래스를 사용하는 이유를 설명하겠습니다.

추상 클래스를 사용하려는 이유는 행동을 공유하려는 상황 때문입니다.

예를 들어 기본 논리에서 상속되는 모든 클래스에서 공유하려는 함수 스텁 또는 추상 함수를 작성할 것입니다.

또한 변수를 공유하고 싶지만 이 특정 변수는 public이 아닌 보호되어야 합니다.

그리고 인터페이스를 사용하여 이 작업을 시도하고 수행하려는 경우 해당 특정 값은 반드시 공개되어야 하며 일반 유형도 사용하게 됩니다.

그 방법을 알려 드리겠습니다.

따라서 일반 유형의 구문은 꺾쇠 괄호를 사용하는 것입니다.

그런 다음 이 꺾쇠 괄호 사이에 문자 그대로 원하는 모든 것을 사용할 수 있습니다.

But my suggestion to you is to not use something which is already used, hence why I'm using this all capitals event.

Now, if it doesn't make sense what we're doing here, it will make more sense when we write the classes which inherit from base logic.

Let's go ahead and finish this off.

To briefly explain the intent of this abstract class.

Basically, I'm saying that I want a set of classes, the ones which will inherit from base logic, all of which will have this function on event.

In other words, these classes will handle events from the user interface.

And then as we'll see, we're going to use this job object which comes from the coroutines API as a way to Cancel child co routines.

And also to make each of these logic classes as its own co routine scope.

I'll explain that when we get to that particular part of the tutorial, right click on the common package and create a new kotlin file, which is just going to be a plain old file, and it's going to be called extensions.

gotlands extension functions and extension properties are among my favorite features of the language as a whole.

Without getting too technical here, extensions allow you to employ the open closed principle, which states that software entities should be open for extension, but closed for modification.

If that doesn't make sense, don't worry about it is kind of a confusing definition.

But it allows us to add new functionality to existing source code without having to modify the original source code.

Now, this particular file extensions.kt is kind of like a replacement for static utilities that we might have used in Java or something like that.

It's really just a place where you stick utility code which is used across the application.

Let's write our first extension function to see how this works.

The purpose of this particular extension function, obviously it will be used within activities is really just syntactic sugar, its way to make it so that I don't have to type out toast dot make text and supply this message toast dot length long and dot show.

Instead, in the activity where we'll be using activities, I should say where we'll be using this particular extension function, we can just type make toast, give it whatever string we want to display, and it's handled like that.

By making it an extension function of the activity class, I can use it seamlessly in any activity.

Let's write another much uglier utility extension function.

The purpose of this ugly little function here is to take the elapsed time of the given puzzle which the user is currently working on, and to attempt to convert it into a value based on minutes and seconds or a string to display based on minutes and seconds.

Now, if it takes the user longer than an hour, then we end up just displaying like a generic more than 5959.

Now if you think this code is ugly, in kotlin, I challenge you to write it in Java.

Now for beginners, this might not make sense intuitively, but it's important to understand what this is referring to.

This is actually referring to the long object, which we will be calling dot two time on.

That might make a little bit more sense when we actually get to using this particular extension function.

There's only one more extension, we need to add, and it's actually going to be an extension property this time.

So what I'm doing here is I'm hitting alt, enter on this particular red thing, and then I'm going to hit Add remaining branches.

going to hit alt enter, again, to import our, these are obviously string resources.

That's one thing, we're not going to be writing by hand.

So hopefully, what you've done is you've gone and grabbed the source code for the starting point, which includes things like string resources, right click on the common package again, and we're going to create a new kotlin interface, which is going to be called dispatcher provider.

This interface is very small, what we'll do is we'll write the code and then I'll briefly explain what it does.

Now, unfortunately, I can't briefly explain what a co routine context is.

But I can't explain the purpose of this particular class and how we're going to be using these co routine contexts.

So in most situations, most of the work that we're going to be doing within co routines land is going to take place on the main thread or the UI thread.

Now, with that being said, there are a few operations like writing to a file, which we don't actually want to occur on the main thread.

And that would be a situation where we're going to provide the IO context.

Now, the actual purpose of this particular interface is really key here.

What we're going to be doing is that if we wanted to hypothetically test any class, which needs to use these co routine contexts, in a JVM environment, so not an actual running application, then what we could do is we could return a particular kind of CO routine context, which allows us to test in that particular environment.

I know that's a lot of technical detail, but I can't really make it a whole lot simpler than that.

However, by using this interface here, when we want to use our co routines in the production environment, we can provide the real UI main thread context for the front end, and then we can provide a real dispatcher for the IO thread.

To make that even simpler, we're really just making the code easier to test.

Right click on the common package, go to New kotlin file or class, this time, it's going to be an object.

And hopefully I can spell this right production dispatcher provider.

Again, what we'll do is we'll write the code here and then I'll explain how it works afterwards.

I'm going to hit alt Enter again.

And this is where we will return the actual dispatchers that we'll be using in production as per the name of this particular object.

Now there's a number of reasons why I'm using the object keyword here.

So basically objects in kotlin are in this particular case Singleton's.

So that basically means that we will only ever have one of these production dispatcher, a provider software thingies floating around in memory space at one particular time.

They're also thread safe, which is important because although co routine is not necessarily a thread, our dispatchers dot main and dispatchers.io has something to do with threading.

And the other thing that an object can do is it can actually inherit from an interface.

Now we're not actually going to be writing any unit tests in this particular application, which require the dispatchers but just to show you What you would do if you wanted to unit test some class which needs to use these co routine context, what you can do is you can just instead return dispatchers dot unconfined, and then you would return that for both the IO context and the UI context.

And then that is what you would use in like a JVM j unit test environment.

The persistence package contains classes and functions, which have the role of persisting or storing data beyond the lifecycle of an Android process.

If you don't know what a process is, it simply means a program which is running on a device.

Practically speaking, we will store the progress which the user has made in the current Sudoku game, as well as the settings for that game, and the user's personal records or statistics, as I call them.

Here's a quick look at the architecture of the persistence package.

The game repository in this situation functions as a back end decision maker for the two data sources, which coordinates the data sources themselves.

Just try to carry out CRUD operations, create, read, update, delete, and either report with a success or a failure if an exception is thrown.

The general principle here is to keep things together, which makes sense to be kept together to separate what doesn't need to be kept together, and to also use an abstraction or an interface.

In any place where the implementation might change, I might decide to stop using the local file storage or proto data store.

So hiding these details from the repository is not over engineering, but rather a calculated decision.

Speaking of data sources or storage mechanisms, we will use two different mechanisms for storing our data.

Firstly, we will store the user's preferred Game Settings and their personal statistics in protro data store data store provides a lightweight and efficient way to store this kind of data using protocol buffers.

Protocol Buffers is a serialization language similar to JSON.

However, I find it easier to read than JSON.

And fortunately, the library we will use also comes with its own protobuf compiler that will generate some of the boilerplate code which we would otherwise need to write ourselves.

We also use the device's file storage to store the progress of the user in the currently active game.

Every Android app is given some memory space to store files, which is what we will use.

This is done by making all of the domain models implement serializable.

And using Java as input and output streams to read and write objects from kotlin language.

So in case you aren't following along with the tutorial, and you haven't downloaded the starting point repository, what you're going to want to do is you're going to want to add a directory called pro tau in the main source set, the starting point repository should already have that directory.

So just go ahead and right click on it, and go to new file.

And this file is going to be called gain underscore settings, dot proto, and make sure it's all lowercase.

Go ahead and type this in the top of the file.

So protocol buffers are essentially like a serialization language.

It's very similar to JSON.

If you want to look more into it, you can about what the benefits and the pros and cons of using something like JSON.

But personally, this being the only project that I've used Protocol Buffers in so far, I'm quite happy with it.

Okay, so let's just add two more lines.

And I'll explain some more from there.

Okay, so we'll talk a little bit more about this in a moment.

But basically, what's going to happen here is, we're going to define this protocol buffer message, as it's called, which is kind of like a data type for lack of a better term.

And what we can do is, so this file will be consumed by something called the protocol buffer compiler.

And in this case, what we're basically telling it is that we're going to be generating Java files.

Now in the generated class files.

The protocol buffer compiler is going to basically add whatever we put in the Java package as the package for the generated Java class file.

It's just useful to not mix up your namespaces and stuff like that.

And as for the second option, here, Java, multiple files.

If you don't have that turned on, then what can happen is that basically, the generated Java files will all be in one single file.

We don't really want that, although I'm not sure if it's absolutely integral to getting this application to work.

Like I say, we're going to go through this pretty practically and I'm not an expert in protocol buffers.

Okay, now, we're going to do Line a message which is kind of like one of the main data types for lack of a better term in this particular language.

Okay, so let's talk about what we just did here.

So we've defined a message, which in Protocol Buffers is kind of like a data type or a collection of fields.

And we've done two things.

So within the game settings message, we have a 32 bit integers, like a kind of a smaller integer to represent the boundary of a Sudoku puzzle.

So when I say boundary, I mean like a four by four Sudoku puzzle will have a boundary of four, a nine by nine Sudoku puzzle will have a boundary of nine, obviously.

And the other thing we did here is we defined an enum in protocol buffers.

Now when you're creating these enums, you'll need like a default value unknown.

And then you've got the other values that the enum can potentially be.

Also notice how in boundary and difficulty the fields above the enum I'm giving it default values, naturally, those will be like the values that the protocol buffer gets pre loaded with, like the first time you access it.

Now, the important thing to understand here is that assuming you've added the support for Protocol Buffers into your build Gradle configuration, the proto buffer compiler is going to actually generate some Java files or classes out of this particular message.

Okay, so what I'm doing here is I've opened up the completed project, and I'm just having a look at the file which was generated by the protocol buffer compiler.

And all I really want you to notice here is that when you're using proto data store, what's going to happen is it's actually going to generate a Java class for you.

Obviously, you can see we have our gain settings in camel case, which is what we defined as our message.

And then we also have that enum defined below.

So what does this actually do for us, basically, this is going to allow us to serialize or basically translate from Java into the protocol buffer language and vice versa.

And it also means that we don't actually have to create our own plain old Java object in order to do that.

The library is going to generate that for us.

But we can still use it in our code, which we'll do in a moment, we're going to add one more proto file.

So go ahead and open up the protobuf directory, right click again, go to file.

And this one's going to be called user statistics dot Proto.

Alright, so I've just copied and pasted the first three lines from the other protocol because we'll be reusing them.

And we are going to create another message here.

Now when I say statistics, this is kind of like my way of talking about the user's personal records.

So what are the shortest times to completion that a user has made in solving a particular size and difficulty in a particular Sudoku puzzle? It's pretty straightforward.

So let's just write it out.

And there you have it.

Now, you might be wondering why I'm using 64 bit integers here.

So these actual values are going to be stored in milliseconds, which is why I do want the 64 bit integer storage there instead of the 32 bit integer.

I'm not actually 100% sure if that's necessary, but I did that just to be safe, and realistically, it's not really going to eat up that much extra memory.

Okay, so that's it for our protocol buffer files.

Now, we're going to have to create some protocol buffer data stores, which is how we're actually going to create and access our protocol buffers.

Go ahead and right click on the persistence package, go to New kotlin file or class and this is just going to be a file called data stores.

Okay, so before proceeding, you're going to want to go to build and make project.

Now the build will probably fail, but all we really wanted to do is to generate the appropriate Java class out of the protocol buffer.

But if for some reason that doesn't work for you, just follow along, and eventually it will work.

Okay, so for each protocol buffer based data source, we're going to need to provide a way to get ahold of it or create it from context, then the other thing we'll need is a serializer.

Go ahead and import everything.

And there's two things we need to add into the delegate here.

Okay, so don't worry that it's showing up red will actually write this serializer.

Next, so I just wanted to explain what's going on here.

So we're creating a data store object, and it takes the protocol buffer generated Java class, which is called Game Settings.

And essentially, what this does is it creates a reference which which we can use to either store or retrieve our protocol buffer.

Now, you might be wondering what game underscore setting.pb is, and why it has a different file extension than our proto files, to the best of my understanding game underscore settings.

PB is something that's generated after the fact by the compiler, whereas the profile is something we write for the compiler to consume.

But in case I'm wrong on that, then feel free to flame me on Twitter.

The other thing we'll need is a serializer, which takes care of serialization quite obviously.

After that, you can just click here, hit alt insert, override methods, and we only need the methods from the serializer interface.

So again, let's read the code and then I'll explain what I need to explain after the fact.

Okay, so I'm going to keep the details here pretty light.

So obviously, when we create our data store, it's given the game setting serializer here.

And what the serializer does is it helps us to read and write from input streams.

So in other words, we're going to be obviously reading from a protocol buffer file, and then that's going to be serialized, or rather D serialized into Java, and vice versa.

So basically, what the Android team has done for us here is they've made it a lot easier to handle things like error handling and dealing with input streams.

Because if you've ever worked with input streams in Java, then you can tell there's, you know, you're probably familiar with a lot of boilerplate code to do with that.

So basically, we do a little bit of boilerplate work here.

And it translates to a very simple API, when we actually want to read and write with this particular tool in the back end, which we'll be doing in a moment.

Okay, now, obviously, we need to write another data store and also serializer for the other data type.

So this is going to be one of those rare scenarios where I do actually just copy and paste because there's absolutely nothing new, we're just going to change a couple of the words.

So this would be one of the points where I encourage you to have the complete source code open on the side and then that way, you can do a little bit of copy paste action, like I'm going to do now.

And that is our data stores file complete.

Now obviously, if you had a whole bunch of these, you'd probably want to use separate files, but since I only have Have the two I just decided to stick them in the same file, right click on the persistence package and go to New kotlin class.

This one's going to be called local game storage ample.

So firstly, we're going to make a constant which will represent the name of the text file that we will be reading and writing the game data to.

Next, we'll create the constructor.

So you might be wondering where a file storage directory comes from.

When we create the build logic of this application, which is kind of like my inversion of control dependency injection type stuff, what's going to happen is we're going to call this one function to the Android system, which will return us the specific directory from the system where we can read and write things like files.

Let's go ahead and implement the interface.

Now, I'm going to try to get through this relatively quickly.

But one thing I want to explain is that you'll notice I'm making fairly extensive usage of helper functions.

The reason for that is just to avoid writing redundant code.

Also, as with the other implementations, we're going to be using the width context co routine builder to do this kind of IO work off of the main thread.

So what we'll do is we'll call a helper function called update game data, and we'll pass it in the game data.

And if that operation happens to be successful, then we'll actually just return the same game object that was passed in because it should be consistent.

Okay, now we can create the helper.

So here, we're going to throw the exception so that it'll actually get picked up by the catch block in the functions that we'll be calling this helper.

Now, we're going to be using input and output streams, which are part of the Java standard library in order to rate our data to and from the file.

If you're wondering kind of what this word stream means, ultimately, what we're actually doing kind of at the low level, is we're going to take our game or Sudoku puzzle object, and we're going to serialize it into basically a stream or a very long sequence of textual characters.

And that's what we'll actually be reading and writing from the file.

Okay, so two points, you always want to close your streams.

Also, you might be wondering, how is it that we can say dot write object and pass in our Sudoku puzzle, but let's just check the parameters here.

So I'm going to hit Ctrl p within the parameter brackets, and as you can see, it accepts any type.

Now the important thing is that if our different classes like Sudoku puzzle and Sudoku node did not extend serializable than we wouldn't be able to do this without errors.

So for update node, it's a little bit different, we're just updating one individual node.

So how this is going to work is we're going to get the old data and then we're just going to update that individual node.

And then we will rewrite the result back to storage.

So get game will be another helper, we write, and what I'm going to do is I'm actually going to write that one right away.

Otherwise, the autocomplete and error handling stuff will be all over the place.

Okay, that's what we need to do there.

Now, just a quick reminder here, when we say color, and really, whenever anyone talks about a color in a graph data structure, they're really just talking about a number.

So in this case, the number represents the actual value placed in a particular Sudoku square.

So it'll be like something from one through nine, or one through four, depending on the boundary of the Sudoku will also update the elapsed time.

After it's updated, we will write that result to storage hopefully.

And just to keep the front end synchronized with everything else, then we will return that same game object.

Now it has just come to my attention that I have forgotten to add a particular integer called color to this particular function when I wrote it, so let's just go ahead and fix that now.

There we go.

And I managed to save the easiest for last.

And that's it for this file.

Right click on the persistence package, go to New kotlin class, this one's going to be called game repository info.

So in case you jumped ahead, and you aren't actually familiar with the repository pattern, I actually already explained that in part two of this series where I built the domain package.

In any case, let me just reiterate, reiterate what the purpose of this particular classes, it's basically like a bridge and decision maker for the backend.

Now sometimes you'll have multiple different repositories or datasets.

In the back end, and it might be a good idea to keep them separate.

The reason why I didn't in this particular case is because the game storage and the settings storage are actually inextricably linked.

They are by nature closely related.

So based on that, and the fact that this isn't actually a very large application, I chose to put them together within this repository.

And then how it will work is that the repository will coordinate these two different data sources.

Let's start with the constructor and the repository interface.

Okay, so as you can see, we have our work cut out for us.

So what I'm going to do is I'm going to try to write the code relatively quickly.

And after it's written, I'll explain what it does.

So there shouldn't be anything new in this particular function, except for the fact that we're making an assignment statement within a control statement, Val current game result equals etc.

We're allowed to do that because kotlin is a beautiful and idiomatic language.

This one's actually pretty simple.

You know, for the life of me, I don't understand why it keeps putting on air on top.

I'll explain this function in a moment.

So puzzle is complete is actually a function which exists in the computation logic package, which we'll be writing later on, of course, and all it does is exactly what it says.

But it will return either a true or a false based on whether the puzzle is complete or not.

Hence is complete.

Okay, so what I've done here is I've copied and pasted in the plain language use case which describes this particular function.

Now, as you can see, it's pretty complicated to give a basic explanation of what's going on.

And why did this when we request the current game, ie when the application starts up, there's a number of different things that could happen.

So for starters, the user could have a currently active game and they just want to retrieve it.

It could be the first run of the application, so no game currently exists in storage.

And then there are different situations where errors could occur along the way.

This is something that happens when you're coordinating multiple different data sources.

Now I have my own system of tracking these different event streams, I use basically letters and numbers to denote steps and different potential event streams.

But whatever you do, my suggestion to you is to write this down in plain language first and then go ahead writing the code.

That's what I did this comment above you see here, I wrote that before I wrote the code.

Anyways, let's get started.

Okay, so for our first Event Stream, we attempt to retrieve the current game, and that returned successfully.

And then we also want to know whether the current game is complete or not.

We can just get rid of oncomplete.

And here we go again.

So this is obviously the case where the user has first loaded the application and we want to create a brand new game.

And Looks like I'll have to do this manually this time.

The autocomplete is not helping me here.

But in fairness, we haven't written that function yet.

Okay, I'm just gonna double check that I wrote that correctly.

Now, before I want to move on, I want to explain one thing about my perspective on software architecture.

While sometimes in a simpler application, we can do something like have the presenter coordinate different repositories or back end data sources.

In this particular case, there was enough complicated back end logic that I wanted to have also a decision maker class, which happened to be this game repository imple on the back end, and part of the purpose of this class is to take care of the logic of coordinating these different back end data sources, so that I can keep the presentation logic class doing what it's supposed to do, managing presentation logic, and then I have this class dealing with this messy kind of almost business logic type stuff here.

Anyways, we're not done yet.

Okay, so it just occurred to me that I have missed a function in the interface of a game repository.

So let's just go ahead and add that in.

So what I'm going to do is I'm just going to copy update game, paste it down below.

And what we're going to call this is create new game.

And it's going to take in a settings object and that's it.

So that's actually a helper function that I created mostly for legibility, let's just go ahead and add that in right now.

Just another quick note here, you'll notice that I like incredibly long and descriptive names of everything that's going on.

This is largely because I don't have a great memory for fine details.

So by making these things super long and descriptive, I don't actually have to remember them, I can just read my code and pretty much understand what it does.

Even in these complicated situations where we have all these different event streams and interactions occurring, okay, only two more short functions to go.

And that's it for our back end.

In the top level of the UI package, we have four small files, which we will use to create and apply styles, colors, fonts, and so on.

One of those files is the global theme for our application.

And I will show you how to create both a light and dark theme for the app in only a few extra lines of code.

Stay tuned for the end of this section, as I will do a live demo of the different themes.

Right click on the UI package and create a new kotlin file, which is going to be called color dot Katie.

This file will essentially be a replacement for colors dot XML, if you're used to working with the old resources system, which was based in XML, let's create a color object.

Make sure you import the Compose color class.

Okay, so before we proceed, the most important thing to understand here is how to read these particular values.

So the first two characters here 0x.

This basically tells the compiler, which is the program that will be reading this code that this is in fact a hexadecimal number.

The second two digits here indicates the alpha value as a percentage.

Alpha is another way of saying transparency or how opaque something is.

The remaining three pairs are the red, blue, and green or RGB values, again in a hexadecimal percentage, and that's pretty much all there is to know about these different color values.

I've copied and pasted over the rest of the values because there's absolutely no point in either was typing all this out.

But also keep in mind that they have some predefined values such as flack, for example, which you can also make use of right click on the UI package, and we're going to create another new kotlin file.

And this one's going to be called shape.

So in the old view system, when you wanted to do something like creating a background with rounded corners, or a button or widget or something like that, you had to create usually something inside of the drawable folder, which was XML based.

Again, since this is compose, we can just go ahead and do that in kotlin.

Instead, hey, I will just use some default parameters.

Now, this might be your first time seeing the.dp extension, let's just take a quick look at the source code.

So as you can see, you can basically just append it to an integer double and various kinds of numbers.

The important thing to understand here is that this basically tells the Compose framework that we want to use density independent pixels.

If you want a more profound explanation of what exactly those are, I strongly suggest you look into it because it's a little bit complicated.

Suffice it to say that the idea here is to allow the framework to create values for heights and widths and things like that would work across a variety of different screen sizes and form factors.

Right click on the UI package, and we're going to create another kotlin file, this one is going to be called type.

Now in case you're wondering, when we say type, we're not really talking about a type system, or anything to do with type theory, it has to do with type Pog, Rafi or text and how this text is styled or presented.

So again, this is very much the kind of thing that we used to do and styles dot XML, we're basically going to create a bunch of different text styles, which will use throughout the application.

And then we'll kind of see how to wrap those up in a typography object.

And then we'll see how to add that typography object to our sort of global compose theme.

First, let's create a text style.

Sometimes we have a situation where we want to keep a bunch of default values, but we might want one or two values, which are actually passed in as a parameter to create the text style object.

So I'll show you another way to create these text styles using function.

Just gonna do some quick copy paste here.

And then we can override the color.

So again, what I'm going to do for the rest of these textiles now that we've seen everything there is to see here is I'm going to copy and paste them over.

But there is one more thing that's new that we need to create in this particular file.

Okay, as you can see, we've got a couple different textiles here.

So the last thing we need to do is create a typography object.

So basically, what that's going to mean is that we're going to assign some of the text styles that we've created below, which are used in common things like the body text of a particular feature of the application, buttons, titles, that kind of thing.

If that doesn't make sense.

Let's just write the code.

Make sure you select compose dot material, not kotlin dot txt.

Okay, we're just gonna do To more.

All right, and the only other thing we need to do is set up our graph Sudoku theme.

Right click on the UI package, and we've got, you guessed it another kotlin file.

And it's going to be called graph Sudoku themed.

So one of the handy little features of jetpack compose is that it is incredibly easy to create a theme for light and dark modes.

As someone who uses generally speaking, dark mode almost always actually really appreciate this particular feature of compose.

The first step in that process is to create two different color palettes.

Let's start with the light color palette.

So some of these properties should probably be familiar to most Android developers like having a color primary.

That's how we used to do it also in the old XML system with colors, or at least that was a common naming convention.

Now, one thing I want to point out here is that there's a degree to which some of these more obscure ones like primary variant surface on primary and so forth, I'm really just using those because it's convenient, they don't necessarily have to mean anything in particular.

But the important thing to understand here is that if there's any different color between a light theme and a dark theme, we do want to define it somewhere in here, and then use it appropriate in the composable, which we'll be learning to do later on.

Okay, that was actually supposed to be uppercase there by convention.

And also notice that I've copy pasted over the dark color palette, because again, there's nothing new going on there.

The next step, however, is very important, we're going to create our theme, and it's actually going to be really, really easy.

Here's a little shortcut I learned from a friend, if you want to create a composable function really quickly start typing comp, and then hit enter, just saves you a little bit of time.

Now this theme is going to have two parameters here.

So before we write the body of this function, I just wanted to discuss these two parameters.

So as you can see, we're actually making a function call is system in dark theme, what's going to happen is this system call will return a Boolean, which will tell us whether the user has specified if the app is supposed to be in dark mode or light mode.

And then the content represents everything that will be wrapped inside of this theme.

What's important to understand here is that everything that we put inside of this composable, ie the content will have access to all these different colors, styles and typography information from within the theme itself.

The actual utility of this will make a lot more sense when we actually write the composable.

Just to finish things off, we're going to create a material theme composable.

And we won't need the lambda expression.

So there you have it, it only took a few minutes to create like the color resources and styles and typography information necessary to render both a dark color palette and a light color palette for different modes.

What I'm going to do is show you a quick demo of what this actually looks like in an application.

Here I'm going to be starting the application in the light theme.

Then I'm going to navigate to the operating system settings and set it to a preferred dark mode.

And upon returning we see immediately that the application now is using the dark theme.

We're now ready to start building our user interface.

The UI components package contains reusable elements of the user interface.

Since this is a very small app, the only two such elements are a toolbar, and a loading screen.

One of the great features of compose is that we can make our components reusable in different ways.

Firstly, if a component needs to be positioned according to where it fits in different parent composable, or parent screens, we can pass in a modifier instead of creating a modifier within the child composable.

This is worth experimenting with in case you haven't already.

Secondly, it is possible to pass in composable as arguments, which also allows reuse and extension of functionality.

In this app, we want different toolbar icons for the two different UI screens.

And we can achieve this by passing in the icon compostables.

From those parent UI screens, you'll see later on how we can specify and handle different icons and different click events.

Using the same toolbar will also create this reusable loading screen and later, I will show you how to animate it, right click on the UI package and go to new package.

And this one's going to be called components.

Just a brief explanation here, I've adopted this particular convention from the composed samples repository.

So what will go into this particular folder are composable, which will end up being reusable across a variety of different UI elements and different screens.

In this case, we're going to be creating a reusable toolbar, and also a reusable loading screen, right click on the components folder, and go to New kotlin file, and this one's going to be called app toolbar.

Let's create our functions stub, what I'm going to do is I'm going to type co MP and then the autocomplete will create a composable function.

This one's going to be called app toolbar.

First, let's write the parameter list and I'll explain it a little bit.

Make sure you select the compose.ui modifier.

Let's start by talking a little bit about modifiers.

So modifiers are basically how you can create most of these styles size and position kind of data for a particular composable.

Now there's kind of two different main ways to do this.

We could of course, create this modifier and use it within this widget.

But that would be for a situation when the widget itself is going to be deciding that kind of information.

Since we're using a reusable component here, an app toolbar, which we plan to use in multiple different places.

In this particular situation, we're going to pass the modifier into this function, which is a way of basically saying that the parent composable will actually decide where to position and how to size this particular UI element.

The title is pretty self explanatory, but what is a little more complicated is the icon.

And again, that will be dictated by something in the parent composable.

That's how I actually make this thing reusable and allow it to handle different icons or different actions when it's clicked.

After we finish off this particular composable, I'll show you a quick preview of the actual icon that we'll be using.

So hopefully that will make a little bit more sense.

The first thing we want to do is override the top app bar composable.

Let's just pause a moment and talk about different colors.

So one way to solve this problem would be to hard code some kind of color in here.

But in the previous section of this tutorial, we went through the trouble of setting up both a light and dark theme.

So what we're doing here is we're actually going to be using a color which is based on the theme.

Remember in the graph Sudoku theme composable, there was a call to a function which was his system and dark theme or something like that.

And that's actually going to dictate which color palette we select.

So by using material theme colors dot primary, it will automatically inherit the appropriate color based on whether we're in light and dark mode.

And that would be one reason to avoid hard coding something in here.

In this case, we have a color which will be the same regardless of whether it's light or dark mode.

So we're just going to add in a text composable which is effectively eight Extra view.

But if you wanted to add something like a logo for the application in front or after the title text, and what you could do is you could add in a row here and then just add in both the icon and then the text composable.

And then you'd be ready to go.

Go ahead and import that.

This is probably pretty self explanatory.

But when we want to inherit style data for particular fonts and stuff like that, then this is how we can do it.

Again, this is something super handy.

And you only see this in kotlin, certainly not Java.

So what we're doing here is we're explicitly asking is the application currently in light mode, and then we're picking a text color based on that.

This is really just an alternative way of handing this conditional UI logic without having to assign something to a theme specifically.

Next, we'll deal with alignment.

And that's it for the texts composable in our toolbar.

So action bar is probably something that will be more familiar to the older Android developers.

But basically think of this is like the icons within the toolbar.

Generally, they're used for very important actions in the user interface, like navigating to a new feature, indicating that you're done doing something.

And note importantly, that this particular lambda function is of type row scope.

So basically, what that means is, if you have several action buttons, you can place them within these two brackets here, and they will automatically be lined up like a row.

Now all we need to do is just type icon and then add in the parentheses here.

And this is because we're actually going to be passing this icon in from the parent composable.

As I said, moments ago, I just wanted to give you a sneak preview of the icon itself.

We're not going to be writing it yet, but we will do so later on.

The important thing to understand here is that we're deciding about how to handle on click and what this thing actually looks like in the parent composable, we're not actually doing it within the toolbar.

And by pulling that responsibility out of the toolbar, that's how we get the reusability that we want.

Right click on the components package, go to New kotlin file, and this one's going to be called loading screen.

Let's create our loading screen composable.

The first thing we'll need is a surface.

So you might be wondering, why are we using a surface here in particular, in this case, I really just want like a space surface of the UI, which has a particular color and specific dimensions.

Here I've set Phil max height to a fraction of point eight F, which is basically saying I want it to take up most of the width, or sorry, most of the height of the user interface.

But I might want some space for something like a an ad banner or something of that nature.

Anyways, I basically want an icon or an image which is stacked on top of a progress bar which will be stacked on top of some kind of like text.

So for that kind of situation, obviously we're going to want to use a column.

Obviously, we'll be centering things.

Go ahead and import that.

Now I'm noticing it's not improperly importing our I think there's something within the Compose libraries, which basically mimics our so let me just fix those imports before we proceed.

As you can see here, I've just copy and pasted it in the our import.

And now we're good to go.

That's our logo.

Here's your progress bar.

Okay, so you might be wondering about this painter thing.

So basically, in the alpha version of compose, we had to specify whether it was a vector asset or a bitmap asset and stuff like that.

So we can just use this generic painter resource thing and point it to basically anything in our drawable.

And it will actually figure out whether it's a bitmap or a vector asset.

Also, I wanted to point out the copy function here.

Suppose you have a color and you want to slightly change the alpha value or you have one of these textile objects and you want to make some kind of change to it.

The copy function is super handy for doing that.

In this part of the tutorial, we will create the event sealed class view model and presenter for the act of game feature.

Before we do that, let us look at a few design decisions involved in this architecture.

The purpose of our presentation logic class, which I call logic, for short, is exactly as the name implies, it handles the work of coordinating the container view model and backend repositories.

If notified of a non stop event, it will also cancel all co routines, it does not possess any Android platform code, which makes it loosely coupled and very easy to test.

I might also consider reusing it for a desktop version of this app.

But we'll see.

The purpose of the view model is also to do exactly what the name implies, it is a virtual representation of the user interface, which the view observes.

In simpler terms, it is a model of the view, it exposes function types, which is a very simple and easy standing for the observer pattern.

In situations where we don't require multiple observers.

Each time our logic class updates the view model, the view model will automatically publish the new data to the view.

Another design decision with this view model is that it does not extend jetpack view model.

There are several reasons for this decision, some of them simple, and some of them quite technical.

The simple reason is that using jetpack view model creates tight coupling with the Android platform.

And it has its own set of boilerplate code and dependencies, which I'm not a huge fan of.

In short, it doesn't solve more problems than it creates in this particular application.

And I wanted to practice creating view models which might be usable for kotlin desktop or kotlin.

j s.

The technical reason why is that in this application, we simply don't need to persist the data across activity instances or process death in order to have a good user experience.

Instead, we just make a fairly cheap call to the Android file system and reload the data from there if such events occur.

Now, before you apply that reasoning in every situation, understand that reloading data from a file system works fine in this application, but should not be considered a suitable replacement for unsaved instance state in every application you write.

If you like the models in save state handle, go right ahead and use it.

We also employ the strategy pattern to clean up the interface which our logic class exposes to the container in the view.

Each subclass of the sealed class represents an action that can occur in the view or container.

Rather than having a function for every UI event.

We have one function that accepts a single object that can represent multiple different paths of execution.

That's the strategy pattern.

Right click On the UI package, and go to new package called active game, right click on this new package, go to New kotlin file or class, and we're going to create an interface, and it's going to be called active game container.

This word container is a technical term.

The way I'm using it here is to kind of signify something which contains a large portion of an application or an entire application.

In my opinion, a container doesn't usually deal much with the business kind of logic of the application.

It basically just wires things together and builds things and kind of serves as an entry point.

In the next part of this tutorial, I'll explain what we'll actually be using as a container.

But by using an interface here, I'm basically stating quite explicitly that I might change my mind about what we use as a container.

Anyways, it only contains two abstract functions.

Right click on the active game package again, and we're going to create a sealed class this time.

And it's going to be called active game event.

So as I explained in the above comment, the active game event sealed class represents every kind of user interaction of a given feature, in this case, the active game feature.

This is a very common pattern that I use and we'll see how it works with our base logic abstract class which we created in the common package.

Okay, we are now going to create our view model.

Firstly, let's create a small little class here which will be like a virtual representation of a single tile in a Sudoku puzzle.

So obviously, x&y represent the x&y coordinates of the particular Sudoku tile value will represent what we talked about in graph data structures as the color again, it's literally just a number, I don't know why we need to call it a color.

Now it has focused indicates that the user has clicked on a particular tile, after which they can click on one of the input buttons to change that particular number.

And finally, a read only tile you can think of as a tile, which is like a given clue in the puzzle.

So therefore, the user is not allowed to actually change any read only tiles.

So before we start reading this view model, I just wanted to mention a couple of things here.

As discussed in the introduction for this particular section, I didn't actually want to use any of the jetpack libraries to achieve a publisher subscriber relationship between the view model and the view.

Now, it turns out that that publisher, subscriber relationship or pattern is actually quite easy to implement.

But in this case, I actually found it simpler to just use kotlin function types to achieve what I would call a poor person's publisher, subscriber pattern or observer pattern.

So this really means something simple in practice, although it might look kind of complicated for those who aren't really familiar with working with function types.

Our view model will possess these nullable function type references.

As we'll see in a moment, what we can do is each time we update the view model from the presentation logic class, we can then update the view by extension by invoking these function types from within the view model.

Now, the reason why we're using notables here is from within the view model.

I can never be 100% certain if there is actually anything listening.

But with that being said, I feel like if I played around with this particular class for a couple of hours, I could probably streamline a little bit and maybe make some of these internal variables private or something like that.

So really what I'm saying here is Feel free to take this general idea of having a view model, which isn't tightly coupled to Android jetpack, but also feel free to experiment with it and see if you can optimize it.

So with that out of the way, let's create some function types.

So all of these function types will be prefixed with sub to ensure good legibility.

Active game screen state is actually something we will create in the next part of this tutorial.

So just go ahead and leave it glowing red here.

Okay, let me just briefly explain these different function types.

So the board state is basically a virtual representation of the Sudoku board.

Obviously, the content state basically just means three different states.

So either we're loading the data, the user has a currently active game that they're solving, or the user has completed a particular game, we will use this to animate between different states in the user interface.

Now, timer state has to do with the count up timer, which basically records how long it takes for the user to complete a given Sudoku game.

So just to hopefully clear up any confusion here, timer state will be the actual long value in milliseconds representing the time and then sub timer state is the way that we actually update the user interface after we update the new timer state.

Let's finish off the rest of these variables.

These are quite obviously default values.

Next, we'll write a function to initialize this view model.

Okay, so let's just pause for a moment.

What we're doing here is we're taking the state of the data as it existed in storage, we're giving it to the view model, and then what we're doing is we're building the view models own virtual representation of that state.

Now, the view models internal representations will have things like has focus, which are concerned specifically of the user interface and not necessarily something that I would include in the original domain model.

Also, in case you're wondering, the key value is basically created from hashing the x value and the y value.

This is something that we covered very early on in this tutorial, in case you've jumped ahead.

Again, active gain screen state is something that we will create in the Compose part of the tutorial.

Here, we're binding that data to the view model.

And then we will invoke our function types to update the view assuming it's listening.

And that's it for our init function.

Now, we just have a few more functions, which will be called by our presenter to do various things with the state of the view model.

So here, we're just updating an individual tile.

So what we're doing here is when the user hits a particular tile, that's going to send a message into the presenter, which will have a particular x and y coordinate, and then the presenter will call this particular function.

And so what it will do is it will look for the tile which the user clicked on based on that X and Y value, and set that one to has focus equals true.

And then for every other tile, we want to set it to false.

Otherwise, we could have a situation where the user has selected multiple different tiles, which is not something our application is supposed to be allowed to Do and this would be the situation where our back end has determined that the current puzzle is complete.

Right click on the active game package.

And let's create a new kotlin class, which is going to be called active game logic.

Okay, so before we proceed, this is definitely one of those situations where I strongly suggest having the complete source code open on the side while you follow along here.

Obviously, I'm going to do my best not to make any mistakes, but it's possible that I will make a mistake.

Active game logic represents the presentation logic of this particular feature of the application.

As we'll see, it coordinates between the container the view model, and then by extension, the view, as well as the back end of the application.

Let's start with the constructor.

Okay, so just a bit of review before we move on, for the time being the container will actually be an activity.

But there's a possibility in the future, I might move to using fragments as containers instead, at this point, I don't really want to, but we'll just see if that makes sense in the future.

But this is the entire reason why I have included an interface here so that I can change what's behind the interface very easily.

The view model is pretty clear, we just wrote it.

Game repo is where we store the game data.

So that includes the game settings as well as the current progress of the users game stats.

repple is where we store the records for the shortest times to completion of each different difficulty and size of puzzle.

And if you're wondering what the dispatcher is go back and watch the common package when we created that we created this dispatcher provider and I basically explained what the purpose of it is there.

Base logic is also something that we created in the common package.

And we'll see the function that we inherit from that class in a moment.

Okay, let's start for a moment about co routines.

So one way to think about scopes, whether we're talking about co routine scope, or dagger or whatever, is to really just consider that it's about a life cycle.

Now, you're probably wondering, why are we not making something like a view model or a fragment or an activity, our life cycle class? Well, in case you haven't noticed by now, I don't like any kind of tight coupling to the Android platform, if I can avoid it.

There's a number of other reasons.

But one of the main ones is that because this class contains all of the presentation logic, in a sense, it's the head decision maker for this feature of the application, then, in my opinion, it makes sense to make it responsible for cancellation of any co routines, which happened to be currently running as far as this on event function, which we inherit from base logic.

Well, basically, this is an implementation of the strategy pattern.

I won't give you a long and technical explanation here.

It's actually a very simple pattern.

But basically, it provides sort of like a singular entry point into this particular class.

So instead of having like a single function, for every event, we have one function, which takes in an argument, our active game event, which is capable of representing all the different events, and I just find that really cleans up the interfaces between different classes, interfaces is used in the general sense in that statement.

Okay, first, let's implement our co routine context.

Remember, jobtracker exists in base logic, but we also need to initialize it Okay, now before we proceed, there's something really important we need to implement which is a ko routine timer.

As I mentioned before, the active game Screen does have a count up timer.

Now some of you are probably going to be wondering, why didn't I use the Java timer class or the androids count up timer or whatever it's called.

Basically, I did try using those things.

And they presented different application breaking problems.

And it turned out to be easiest just to create this kind of CO routine timer.

Okay, so this requires a little bit of explanation, obviously.

So we'll notice two different keywords here, which might be unfamiliar to some of you, we have the inline and cross inline keywords.

So whenever you see the inline keyword, the easiest way to understand that is to understand that it just means copy, paste.

And if you want to know what that means in code, then I suggest you decompile some of your kotlin code, which uses the inline modifier, and you'll see how the inline function is actually copy and pasted into the call site.

Now we have something else going on here, which is a cross inline function type.

So before I explain what the cross inline action is, let's talk about what this function actually does.

So here we have a pretty standard spin lock, while true.

So it's a loop that's going to just endlessly execute, it's going to invoke that function type, and then it's going to delay for 1000 milliseconds.

Now, there's a couple different things going on here.

Number one, you have to understand that we will be delaying this ko routine, but it's not actually going to block the thread that it's on, which is of course a big win.

Now the other thing that's going on here is action is going to be a lambda expression that we will pass into this particular function.

Really the only thing crossing line does is it basically makes it so that in the lambda function, which we will pass into this function here, we're not allowed to write a return statement in that function.

So in the most general sense here, what we're doing is we're taking a preventative step, to avoid a situation where we might accidentally return from within the lamda that we pass in here causing unexpected behavior.

Now, you're probably wondering, since we have this endless loop going on, how do we actually stop this particular core routine? Well, what we're going to do is we're going to create a job.

Let's just do that now.

And what we'll do soon is we will actually assign this job variable to our start co routine timer, and that will allow us to cancel it.

Let's just write another quick extension function to do with this timer business and then I'll explain what it does.

In experimenting with the user interface, how to make the timer the least janky or most accurate that it could be it turned out that subtracting one from the value each time we write it to the back end created a more consistent timer.

But one particular edge case is if the value equals zero, then obviously we don't want to subtract one from it.

Otherwise the timer will say negative one at first and that just doesn't look very good.

Okay, so with all that done, we can get to implementing the rest of the presentation logic Okay, so when the user hits an input button, we can have two different situations that could occur.

In one situation, the user has already selected a tile, which would become the focus tile.

Or it might be that they just hit an input button without actually focusing a tile, in which case, we don't really want to do anything.

Okay, so if you're wondering about the details of game repo, you can go back to the part of the tutorial where we actually build it.

Basically, we're going to be creating a lambda to represent the success case, and then another lambda to represent like an error exception case, to make that a little bit more legible.

I'll just add in a comment here.

Okay, so if you're again, wondering how we actually cancel the timer, this is exactly how we do it, we cancel the job object.

Now we'll write this other function in a moment.

Basically, if it's a new record, then we want to render the user interface slightly differently than if it wasn't a record.

But before we do that, let's finish off the error case.

So in order to actually know if it's record, we actually need to pass the value back into the stats repo just to check on that.

So I'm going to be honest, the error handling in this application is not the best, neither is it really the worst show error Well, for the time being just actually show a toast message explaining that some error occur.

Okay, just a quick fix.

This is actually supposed to be elapsed time not timer state.

Next, we have on new game clicked.

You'll notice a recurring theme here, which is at any time we want to perform concurrent operations.

So anytime we're working with the back end, we're going to wrap that into a launch co routine.

There's a lot of different ways to work with CO routines.

This is just one of the most simple straightforward ways to do it.

In my opinion.

Okay, so what we're doing here is first we're asking the view model has the user completed the current game, if they haven't, we actually want to store the progress the user has made in their current game, when they hit on new game clicked, because maybe they hit it by accident, or they want to be able to go back and finish the game or some reason like that.

That's right The update with time function.

Again, we have success and error cases.

Hopefully, that's pretty clear at this point.

Next, we'll implement that function.

Next, we'll write the cancel stuff function.

So basically, the cancel stuff function essentially cancels every ko routine.

Next, we'll write on start.

I forgot to mention earlier, the reason why we had an underscore in one of the functions for is complete.

It's just kind of a convention for a lambda argument or parameter, which doesn't actually end up getting used.

In this case, we're going to use it.

Okay, so obviously, this is where we start the coroutine timer, and we only want to do that when on start is called.

Now again, I feel like I could have handled this a little bit better, it kind of goes against my rules to consider standard flow the application as an exception.

But basically, what we're going to do here is in the event that we ask the storage for a current game, and it doesn't actually retrieve anything, generally speaking, this situation is going to occur when the user has run the application for the first time, and hence, there wouldn't actually be any data stored.

So in that particular case, we would want to do this.

Now, we could also end up here because of some kind of legitimate exception, but in that particular case, I still think navigating to the new game feature is still actually a good way to handle that good but maybe not the best.

Next we have on stop.

Okay, so onstop is actually tied to the lifecycle of the Android activity or fragment that it's bound to.

So when this function is called, that basically means that we want to save the user's current progress and then kind of shut everything down.

Finally, we have on tile focus.

So this would be when a user actually selects a particular Sudoku tile.

Now this function is incredibly complicated, so brace yourself.

Okay, I lied.

That's actually everything we need to do.

In this part of the tutorial, we will create the user interface for the active game feature.

Before proceeding I strongly suggest you watch my video entitled How to Understand jetpack compose a beginner's guide to composable and read composition.

We will be writing many composable and setting up re composition as well.

But that video is made for people who are just getting started with compose.

It explains what a composable is, what re composition is, and how to avoid doing read composition the wrong way.

And believe me, it is fairly easy to screw up read composition if you aren't aware of how it works.

I will link to this video in the pinned comment below.

This video is full of a ton of information, so please take a look at the timestamps in the description box below.

Topics include basic widgets, such as text, text, button, image, icon, spacer, and divider layouts, such as box column row box with constraints and my favorite constraint layout.

Simple transition animations to animate between a loading screen, active game and a complete game.

I also show you how to communicate with our presentation logic and our view model using function types and lambda expressions.

Before we write the composed code, though, I show you how to set up an activity as a container for composable.

The process for doing this is almost identical for fragments if you prefer them, I also show you how to write a very simple dependency injection extension function, which hides the backend details from the front end.

Right click on the active game package and go to new activity and choose an empty activity.

And make sure you uncheck generate a layout file.

And this activity will be called active game activity.

It will be the launcher activity.

Now in case you're wondering why we're using this wizard instead of just creating a class file.

The reason is simply that by using the wizard it will add an entry into the manifest so we don't have to do that.

Just to briefly recap the purpose of this activity here is as a feature specific container.

Let's start by creating a reference to our active game logic class.

Next, let's implement the active game container interface.

Click on the red and hit alt enter.

For show error, we will use the extension function that we created way earlier on in this tutorial.

Go ahead and import.

Also in case you're wondering, this is single expression syntax here it basically just replaces the brackets and return statement with just an equal sign.

Next one implement on new game click.

Now obviously we haven't created new game activity yet so that will show up as red until we do.

We also need to override two more lifecycle methods.

Here will tell the logic class that everything is ready to go And then we'll also override on stop.

And that will obviously signal the logic class that it's time to cancel things and tear stuff down.

Finally, we just need to add a few lines to on create.

First of all, create the view model.

Now, this is a really important part, what we're going to do next is we're basically going to anchor our composable that we'll be creating in the next part of this tutorial, to the activity here.

This is also something you can call inside of a fragment.

Go ahead and import that.

Naturally, we're gonna wrap everything in our compose theme.

Now, this is a very critically important thing to understand and a very important pattern.

So when we create active game screen, we're going to pass in a function type, which will serve as our event handler, which is basically my way of saying that is the way in which we will forward the events, the onClick events and stuff like that, that occur in the composable to our presentation logic class.

So make sure you pay attention to what I'm saying here, because this is a really important part, even if you don't use presenters wood, or whatever.

Function types are an excellent way to handle on click events, especially if you combine them with the strategy pattern, which we discussed in the previous section.

Okay, now, if you've never seen a function reference, I believe it's called basically what we're doing here is we are pointing to the on event function of the logic class.

This really is a function reference.

So hopefully, you can understand what I'm talking about here.

We'll also pass in the view model.

Now lastly, we actually need to build our logic class.

So what we'll do is we will write that code in an extension function, but what we can do first is just read it here.

And that's everything we need to do in our activity.

Right click on active game, go to new package, and this package will be called build logic.

Right click on that package and go to New kotlin file or classes is going to be a file.

And it's going to be called build active game logic.

If you've been watching my channel, or live streams for some time, you'll know that I talk a lot about dependency injection service locators.

And one of the things I say all the time is that in a small application, you really don't need to use di container, like hilt, dagger, whatever, you can use it.

But what I always advise for beginners is to write the code that these things generate for you, yourself first, so that you understand what these frameworks are doing for you.

So that's exactly what we're going to do.

We're going to write the kind of thing that these frameworks generate for you.

And in a small application, it's actually very simple code to write.

And, of course, it's going to return active game logic.

Okay, let's pause for just one moment here.

So in case you're wondering how we get the path to the storage directory that we can use for this application, you can call context dot files dir dot path.

Finally, our dispatcher.

And that's all we need to do.

Right click on the active game feature, and create new kotlin file called active game screen.

First, let's create an enum.

This enum represents different states, which this feature of the user interface can possess.

The actual state is held in the view model, but we will see how we can update our composable UI by binding to the view models function types we created in the previous part of this tutorial.

Active game screen represents the root composable.

In this hierarchy of composable, it has the responsibility of setting up the core elements of the UI, and also animating between them.

event handler function type reference is how we call back to the presentation logic.

When the user interacts with the application, it must be passed down to any composable, which has such interactions, we also pass in the view model, which is how we actually give the data to our UI.

In very simple language, whenever we have some kind of data or state, which may change at runtime, we want to wrap that data in a remember delegate.

This tells the Compose library under the hood, to watch for changes and to redraw the UI if a change occurs.

Now mutable transition state is used specifically for animations here, so don't use this everywhere.

We will see a more general purpose example of a remembered state later on.

Remember, delegate prepares compose for updates, but we also need a way to actually update the value.

We do this by binding a lambda expression to one of the function types which our view model possesses.

When one of those functions is invoked in the view model, the program automatically jumps to and executes this code within our composable.

This is what actually triggers the re composition.

We have a remembered transition state and a way to update that state from the view model.

Now we need to set up the transition animations themselves.

This is where you can get as creative as you like.

In this app.

Each content state has its own composable associated with it.

We animate between them simply by changing the alpha value or transparency.

Now it was truly up as red a moment ago, the way I fixed that was to manually import the Compose runtime.

So the transition spec tells compose details about what the animation should look like.

Essentially, this means we don't have to write our own mathematical instructions, which is great for someone like me who sucks at arithmetic.

One option for compose is to use the scaffold composable as a skeleton for your UI.

I personally prefer to do this myself, since it's not really that difficult, and it doesn't hide anything from me.

First, we have our app toolbar.

Let's go ahead and create that new game icon.

These icons come from the Compose material library, I highly recommend you use it.

This is how we actually trigger an on click event.

As explained in a previous part of the tutorial, by creating our toolbar icon here and passing it into the app toolbar composable, we make the app toolbar reusable.

Below the toolbar we have the main content of this screen, which can have three different states.

Each time a re composition occurs, this one statement will be executed again.

The act of alpha value will change when the transition animation occurs, thus fading out the previous content state and fading in the new one.

Obviously, we will create these in a moment.

And that's it for our route composable the most complex part of our UI comes from an active Sudoku game.

A nine by nine puzzle has 81 different texts composable, which is a large number of widgets.

The way I went about writing this composable was to think of each part of the Sudoku game as a particular layer or element.

Be sure to avoid writing God composable by making usage of helper functions, which break down the UI into the smallest reasonable parts.

box with constraints is kind of like a composable wrapper, which gives us information about the height, width and other measurements, we can use that information within its lambda expression.

We need to know the screen width in order to determine how wide and tall the Sudoku board should be.

Here we asked for the max width of this constraint layout.

Here we ask for the max width of this layout composable.

But we need that value to be in density independent pixels, and it needs to be relative to the density of the current screen as well.

That's where the two dp extension function comes in.

And it uses the local density to determine that value.

The margin of the board also needs to change based on the screen density.

I arrived at these values simply by testing the app on various densities using the emulator.

Next, we will write a constraint layout, which is a totally awesome way to manage dynamic layouts.

Now in order to constrain composable to each other, we need a way for them to reference each other.

This is equivalent to setting IDs for XML views.

First, we create these references and you will see how to bind them later on.

Let's create a layout container for the puzzle board.

Okay, so this is really important see how we're passing in that reference in the constrain as parameter there.

This is how we actually associate a particular composable with a particular reference.

This box composable will be associated with the name board.

Next we'll create the Sudoku board itself.

Again, the boundary is like the size of the puzzle.

So it's either a four by four puzzle or a nine by nine puzzle.

So boundary would either be four or nine.

This is supposed to say size.

So the offset here is used to evenly distribute the screen real estate for each Sudoku, tile and grid line.

Here's a way to make a mutable state which is not associated with some kind of transition animation.

So this is the more general purpose approach.

So the first argument here view model dot board state can be thought of as the initial value, never equal policy ensures that even minor changes in the state like has focus actually triggers a re composition.

Again, this is how we actually update the value once the view model is updated.

As you can see, here, again, I'm making usage of lots of helper functions to break things down.

Here we render the text fields which represent tiles in the puzzle, they can either be read only or mutable, thus, meaning that we need to render them slightly differently.

So here, we're saying if the user sets a particular tile to a value of zero, we actually just want to render it as an empty tile.

The main idea here is that we're using the x and y values of each individual tile along with the offset in order to evenly position each tile So when the user selects a tile, it's going to become focused and we want to render that tile obviously a little bit different than an unfocused tile.

Now we'll render the read only squares.

Next we'll create the board grid.

So Sq RT is an extension, which is actually defined in the computation logic.

In retrospect, I probably should have defined that in the common package, but it's pretty obvious what it does.

So this function here, we'll draw the grid lines that separate the Sudoku puzzles.

To make it more obvious to the user which sub grids are which we draw different borders to separate the four by four or nine by nine sub grids.

This is why we're using modulo here.

So this will draw both the vertical and the horizontal lines.

Okay, so we're jumping back into the game content composable to finish it off.

below our Sudoku board, we have some different icons to indicate the difficulty of the puzzle.

Next we need a layout container for the count up timer that's great, the timer texts composable.

Now the default value, it's just empty.

Okay, we're back in the game content composable.

The last thing we need to do is just add a layout container for the input buttons.

Now we're about to hard code some values in here and that is kind of bad practice.

But the reason is that the Compose team deprecated flow row, which I'm still upset about, and it worked perfectly for this situation, and I've been too lazy to implement flow myself.

Hey, at least I'm being honest.

In case you're wondering, 0.4 and five dot dot nine will emit a range inclusive of those values.

Let's create that composable a spacer is pretty self explanatory, it just takes up some space in the layout.

Next we have the buttons themselves.

This text button wrapper allows us to style a nice looking button instead of just adding on click on a text composable.

Alright, that's it for gain content.

Now we need to do the game complete content screen, which is obviously when a user finishes a game.

So this is basically just two images stacked on top of each other, but we're only going to render one of them if it is actually a new record that the user made.

So since we don't actually create the emoji events icon, we can change the color of it using this color filter thing.

Pretty handy.

Next, we have two texts composable.

And that's it.

축하합니다.