<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Thành Toại on Medium]]></title>
        <description><![CDATA[Stories by Thành Toại on Medium]]></description>
        <link>https://medium.com/@thnhtoi?source=rss-f45a72911603------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*1O5WdHMOYBHIqOlQWbaLrQ.jpeg</url>
            <title>Stories by Thành Toại on Medium</title>
            <link>https://medium.com/@thnhtoi?source=rss-f45a72911603------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:14:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thnhtoi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Realm]]></title>
            <link>https://medium.com/@thnhtoi/realm-6ea003d39d3e?source=rss-f45a72911603------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ea003d39d3e</guid>
            <dc:creator><![CDATA[Thành Toại]]></dc:creator>
            <pubDate>Mon, 03 Feb 2020 09:51:39 GMT</pubDate>
            <atom:updated>2020-02-07T10:11:44.232Z</atom:updated>
            <content:encoded><![CDATA[<ol><li><strong>Giới thiệu:</strong></li></ol><ul><li>Khi thao tác với một ngôn ngữ lập trình bạn cần có nơi lưu trữ dữ liệu của mình. Trong Swift ngoài CoreData sử dụng SQLite thì Realm là một lựa chọn thay thế, bài viết này mình giới thiệu một vài thao tác cơ bản với Realm ngay bên trong ứng dụng iOS của bạn để lưu và truy vấn dữ liệu cục bộ lên thiết bị cho phép phát triển ứng dụng một cách nhanh chóng.</li><li>Realm là một NoSQL</li></ul><p>2. <strong>Về cách cài đặt bạn có thể tham khảo link sau </strong><a href="https://realm.io/docs/swift/latest/#installation"><strong>đây</strong></a></p><p>3. <strong>Một số thao tác cơ bản với Realm</strong></p><p>a. <strong>Các đối tượng lưu trữ giữ liệu</strong></p><ul><li>Tạo đối tượng để thao tác với Realm</li></ul><pre><strong>class</strong> MyBook: Object {</pre><pre><strong>   enum</strong> Property : String {</pre><pre><strong>     case</strong> id, name, isCompleted</pre><pre>   }</pre><pre><strong>   dynamic</strong> <strong>var</strong> id = UUID().uuidString </pre><pre><strong>   dynamic</strong> <strong>var</strong> name = &quot;&quot;</pre><pre><strong>   dynamic</strong> <strong>var</strong> isCompleted = <strong>false</strong></pre><pre><strong>   override</strong> <strong>static</strong> <strong>func</strong> primaryKey() -&gt; String? {</pre><pre><strong>     return</strong> MyBook.Property.id.rawValue</pre><pre>   }</pre><pre><strong>   override</strong> <strong>class</strong> <strong>func</strong> indexedProperties() -&gt; [String] {</pre><pre><strong>     return</strong> [&quot;name&quot;]</pre><pre>   }</pre><pre><strong>   convenience</strong> <strong>init</strong>(<strong>_</strong> name: String) {</pre><pre><strong>     self</strong>.init()</pre><pre><strong>     self</strong>.name = name</pre><pre>   }<br>}</pre><ul><li>Đối tượng MyBook được kế thừa từ class Object, đây là một class đặc biệt của Realm, mọi đối tượng muốn thao tác với Realm phải thông qua Object này.</li><li>Có thể tạo mới một đối tượng và gán các giá trị cho thuộc tính của đối tượng theo nhiều cách khác nhau</li></ul><pre><strong>var</strong> mybook = MyBook()</pre><pre>mybook.name = &quot;myName&quot;</pre><pre>// or</pre><pre><strong>let</strong> other = MyBook(value: [&quot;name&quot; : &quot;myName&quot;])</pre><pre>// or</pre><pre><strong>let</strong> other1 = MyBook(value: [&quot;myName&quot;])</pre><ul><li>Realm hỗ trợ hầu hết các kiểu dữ liệu</li><li>Realm chỉ hỗ trợ String, Date và Data là kiểu optional</li><li>Để hỗ trợ Optional kiểu Int ta phải khai báo như bên dưới và gán giá trị thông qua thuộc tính value của RealmOptional</li></ul><pre><strong>let</strong> number = RealmOptional&lt;Int&gt;()</pre><ul><li>Realm cũng hỗ trợ đánh dấu khoá chính(primaryKey) và chỉ mục Index(indexedProperties) thông qua việc override lại 2 hàm của đối tượng Object, điều này làm tăng tốc độ truy vấn giữu liệu.</li><li>Realm hỗ trợ kiểu List để lưu trữ các giá trị trong mảng, tất nhiên các đối tượng trong mảng này phải thuộc lớp Object</li></ul><p>b. <strong>Truy cập các đối tượng trong Realm</strong></p><ul><li>Lấy đối tượng đầu tiên trong database:</li></ul><pre><strong>static</strong> <strong>func</strong> getObjectFirst() -&gt; MyBook? {</pre><pre><strong>   let</strong> realm = <strong>try</strong>! Realm()</pre><pre><strong>   return</strong> realm.objects(MyBook.<strong>self</strong>).first</pre><pre>}</pre><ul><li>Filter trong database: Realm hỗ trợ rất nhiều kiểu filter bao gồm các toán tử so sánh, các tìm kiếm như: ==, !=, BEGINSWITH… tương tự cấu trúc SQL, xem thêm tại <a href="https://realm.io/docs/swift/latest/#filtering">đây</a></li></ul><pre><strong>static</strong> <strong>func</strong> Filter() -&gt; Int {</pre><pre><strong>   let</strong> realm = <strong>try</strong>! Realm()</pre><pre><strong>   let</strong> predicate = NSPredicate(format: &quot;name = %@ AND name BEGINSWITH %@&quot;, &quot;ten&quot;, &quot;B&quot;)</pre><pre><strong>   let</strong> result =  realm.objects(MyBook.<strong>self</strong>).filter(predicate)</pre><pre><strong>   return</strong> result.count</pre><pre>}</pre><ul><li>Chaining queries: Cho phép sử dụng kết quả query của câu truy vấn trước đó</li></ul><pre><strong>let</strong> mBook <strong>=</strong> realm<strong>.objects(MyBook.self).filter(</strong>&quot;name = &#39;tan&#39;&quot;<strong>)</strong><br><strong>let</strong> mnBook <strong>=</strong> mBook<strong>.filter(</strong>&quot;<strong>Any</strong> BEGINSWITH &#39;B&#39;&quot;<strong>)</strong></pre><ul><li>Sort trong database:</li></ul><pre><strong>static</strong> <strong>func</strong> getAll(in realm: Realm = <strong>try</strong>! Realm()) -&gt; Results&lt;MyBook&gt; {</pre><pre><strong>   return</strong> realm.objects(MyBook.<strong>self</strong>).sorted(byKeyPath: MyBook.Property.isCompleted.rawValue)</pre><pre>}</pre><ul><li>Một lưu ý nhỏ là mọi đối tượng trong Realm đều được lưu dưới dạng lazy object giúp quản lí bộ nhớ một cách tốt nhất. Ví dụ:</li></ul><pre><strong>let</strong> results = realm.objects(MyBook.<strong>self</strong>)</pre><p>Nếu trong MyBook chứa 200 records thì biến results sẽ chứa 200 records đó. Tuy nhiên nó chỉ là biến reference đến 200 records đó chứ không phải đối tượng lưu trong bộ nhớ ram.</p><ul><li>Add một Object mới vào database: Sau khi thực hiện hàm write, mọi thay đổi sẽ được tự động cập nhật xuống DB</li></ul><pre><strong>static</strong> <strong>func</strong> add (name: String, in realm: Realm = <strong>try</strong>! Realm()) -&gt; MyBook {</pre><pre><strong>   let</strong> book = MyBook(name) </pre><pre><strong>   try</strong>! realm.write {</pre><pre>     realm.add(book)</pre><pre>   } </pre><pre><strong>   return</strong> book</pre><pre>}</pre><ul><li>Update một Object trong Realm: có nhiều cách update một object trong realm, có thể update theo kiểu primaryKey hoặc update theo kiểu Key-Value code</li></ul><pre><strong>let</strong> myBook = MyBook()</pre><pre>myBook.name = &quot;myBook&quot;<br></pre><pre>// update with primaryKey</pre><pre><strong>let</strong> realm = <strong>try</strong>! Realm()</pre><pre><strong>try</strong>! realm.write {</pre><pre>   realm.add(myBook, update: .modified)</pre><pre>}</pre><pre><strong>try</strong>! realm.write {</pre><pre>   realm.create(MyBook.<strong>self</strong>, value: [&quot;name&quot; : &quot;myName&quot;], update: .modified)</pre><pre>}</pre><pre>// update with Key-Value code</pre><pre><strong>let</strong> books = realm.objects(MyBook.<strong>self</strong>)</pre><pre><strong>try</strong>! realm.write {</pre><pre>   books.first?.setValue(<strong>true</strong>, forKey: &quot;first&quot;)</pre><pre>   books.setValue(&quot;name&quot;, forKey: &quot;myName&quot;)</pre><pre>}</pre><ul><li>Delete một Object: có thể delete một hoặc toàn bộ Object</li></ul><pre><strong>func</strong> delete() {</pre><pre><strong>   guard</strong> <strong>let</strong> realm = realm <strong>else</strong> {</pre><pre><strong>     return</strong></pre><pre>   }</pre><pre><strong>   try</strong>! realm.write {</pre><pre>     realm.delete(<strong>self</strong>) // or deleteAll()</pre><pre>   }</pre><pre>}</pre><p><em>Mỗi lần thao tác với database ta cần phải kiểm tra xem đối tượng Realm này có đang ở trên cùng 1 transaction write hay không?</em></p><p>c. <strong>Migrations.</strong></p><ul><li>Khi làm việc với bất kì cơ sở dữ liệu nào, nhu cầu thay đổi mô hình cơ sở dữ liệu theo thời gian là không thể không có. Vì các mô hình dữ liệu trong Realm được định nghĩa là các lớp Swift tiêu chuẩn, nên việc thay đổi mô hình cũng dễ dàng như thay đổi bất kỳ lớp Swift nào khác. Ví dụ:</li></ul><pre><strong>class</strong> <strong>Person:</strong> <strong>Object</strong> <strong>{</strong><br>    <strong>@objc</strong> <strong>dynamic</strong> <strong>var</strong> firstName <strong>=</strong> &quot;&quot;<br>    <strong>@objc</strong> <strong>dynamic</strong> <strong>var</strong> lastName <strong>=</strong> &quot;&quot;<br>    <strong>@objc</strong> <strong>dynamic</strong> <strong>var</strong> age <strong>=</strong> 0<br><strong>}</strong></pre><ul><li>Chúng ta muốn gộp trường fistName và lastName thành một trường fullName duy nhất thì thao tác đơn giản như sau:</li></ul><pre><strong>class</strong> <strong>Person:</strong> <strong>Object</strong> <strong>{</strong><br>    <strong>@objc</strong> <strong>dynamic</strong> <strong>var</strong> fullName <strong>=</strong> &quot;&quot;<br>    <strong>@objc</strong> <strong>dynamic</strong> <strong>var</strong> age <strong>=</strong> 0<br><strong>}</strong></pre><p>Tuy nhiên, nếu bạn đã lưu giữ liệu trước đó và sau khi thay đổi có sự không khớp dữ liệu hiện có. Khi điều này xãy ra, một ngoại lệ sẽ được đưa ra. Tham khảo thêm tại <a href="https://realm.io/docs/swift/latest/#migrations">đây</a>.</p><p>d. <strong>Notifications trong Realm.</strong></p><ul><li>Realm cung cấp sẵn cho ta một đối tượng là NotificationToken để có thể lắng nghe các thay đổi trong cơ sở dữ liệu như :</li><li>Khi nào được khởi tạo xong?</li><li>Khi nào có dữ liệu mới thêm vào?</li><li>Khi nào có dữ liệu được chỉnh sửa?</li><li>Khi nào có dữ liệu bị xoá đi?</li><li>Hoạt động trên Collection, Results, Object</li><li>Có 2 loại chính Notification trong Realm là Collections Notifications và Realm Notifications</li></ul><p><strong>Collections Notifications: </strong>đăng kí thông báo khi có sự thay đổi dữ liệu như add, update, delete.</p><pre>// tạo đối tượng token</pre><pre><strong>private</strong> <strong>var</strong> token: NotificationToken? </pre><pre><strong>override</strong> <strong>func</strong> viewWillAppear(<strong>_</strong> animated: Bool) {</pre><pre><strong>   super</strong>.viewWillAppear(animated)</pre><pre>   token = books?.observe({[<strong>weak</strong> tableView] changes <strong>in</strong></pre><pre><strong>   guard</strong> <strong>let</strong> tableView = tableView <strong>else</strong> {</pre><pre><strong>     return</strong></pre><pre>   }</pre><pre><strong>   switch</strong> changes {</pre><pre><strong>     case</strong> .initial:</pre><pre>        tableView.reloadData()</pre><pre><strong>     case</strong> .update(<strong>_</strong>,<strong>let</strong> deletions, <strong>let</strong> insertions, <strong>let</strong> modifications):</pre><pre>        tableView.applyChange(deletions: deletions, insertions: insertions, updates: modifications)</pre><pre><strong>     case</strong> .error:</pre><pre><strong>        break</strong></pre><pre>     }</pre><pre>   })</pre><pre>}</pre><pre><strong>override</strong> <strong>func</strong> viewWillDisappear(<strong>_</strong> animated: Bool) {</pre><pre><strong>   super</strong>.viewWillDisappear(animated)</pre><pre>   token?.invalidate()</pre><pre>}</pre><p>Khi không cần sử dụng nữa thì chúng ta nên invalidate() biết đó khỏi chương trình.</p><p><strong>Realm Notifications: </strong>được gọi khi nào có sự commited</p><pre><em>// Observe Realm Notifications</em><br><strong>let</strong> token <strong>=</strong> realm<strong>.</strong>observe <strong>{</strong> notification<strong>,</strong> realm <strong>in</strong><br>    viewController<strong>.updateUI()</strong><br><strong>}</strong><br><br><em>// later</em><br>token<strong>.invalidate()</strong></pre><p>Xem nội dung cơ sở dữ liệu trong Realm: tải Realm Studio theo link sau <a href="https://realm.io/docs/swift/latest/">đây</a>. Sau đó in dòng lệnh này trong chương trình và chạy nó trên terminal hoặc gì đó tương đương:</p><pre>print(Realm.Configuration.defaultConfiguration.fileURL!)</pre><ul><li>Bạn có thể thao tác thêm, xoá, sửa trong Realm Studio và xem cấu trúc database.</li></ul><p>4. <strong>Một số chú ý:</strong></p><ul><li>Không chạy nhiều thể hiện của Realm trên nhiều thread. (Realm có cơ chế tự kiểm tra khi đang được truy cập trên cùng 1 thread hay không, nên khi muốn chạy multithread bắt buộc phải truy cập thông qua ThreadSafeReference)</li><li>Không đọc Realm object từ thread này rồi chỉnh sửa trên thread khác.</li><li>Phải chỉnh sửa dữ liệu trên 1 write transaction của Realm instance.</li></ul><p>Các bạn có thể tham khảo thêm tại: <a href="https://realm.io/docs/swift/latest/#realm-notifications">https://realm.io/docs/swift/latest</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ea003d39d3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Desgin Pattern]]></title>
            <link>https://medium.com/@thnhtoi/desgin-pattern-eb15edfc071f?source=rss-f45a72911603------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb15edfc071f</guid>
            <dc:creator><![CDATA[Thành Toại]]></dc:creator>
            <pubDate>Wed, 08 Jan 2020 09:29:48 GMT</pubDate>
            <atom:updated>2020-01-14T04:19:41.822Z</atom:updated>
            <content:encoded><![CDATA[<ol><li><strong>Singleton</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*hY2G16JQs3CjOriVJ82f3w.png" /><figcaption>singleton</figcaption></figure><ul><li>Singleton là một design pattern thuộc nhóm mẫu <em>Creational.</em></li><li>Singleton cho phép chúng ta tạo ra một thể hiện duy nhất của đối tượng, che dấu sự khởi tạo đối tượng</li><li>Cung cấp một method giúp ta truy cập đến đối tượng ở mọi lúc mọi nơi trong chương trình</li><li>Tuy nhiên, trong một vài trường hợp ta có thể quản lí số lượng thể hiện của đối tượng theo mong muốn của mình mà không phải chỉ là một thể hiện.</li></ul><pre><strong><br>// Lazy<br>lass</strong> Singleton {</pre><pre><strong>    private</strong> <strong>static</strong> <strong>var</strong> instance = Singleton()</pre><pre><strong>    private</strong> <strong>init</strong>(){}</pre><pre><strong>    public</strong> <strong>static</strong> <strong>func</strong> getInstance() -&gt; Singleton {</pre><pre><strong>       return</strong> instance</pre><pre>    }</pre><pre>}</pre><pre>// Khi nào getInstance() được gọi thì đối tượng mới được khởi tạo, hoạt động tốt trong môi trường single-thread</pre><pre><strong>class</strong> Singleton1 {</pre><pre><strong>    private</strong> <strong>init</strong>(){}</pre><pre><strong>    public</strong> <strong>static</strong> <strong>func</strong> getInstance() -&gt; Singleton1 {</pre><pre><strong>      return</strong> singletonHelper.instance</pre><pre>    }</pre><pre><strong>    private</strong> <strong>class</strong> singletonHelper {</pre><pre><strong>      static</strong> <strong>var</strong> instance : Singleton1 = Singleton1()</pre><pre>    }</pre><pre>}</pre><pre>// Tách biệt chức năng khởi tạo cho 1 class function, tăng performance </pre><pre><strong>let</strong> singleton = Singleton.getInstance()</pre><pre><strong>let</strong> singleton1 = Singleton1.getInstance()</pre><pre><br>                          ...................</pre><pre>// Quản lí số lượng instance<br>// Lazy</pre><pre><strong>class</strong> Hall {</pre><pre>/*</pre><pre>private static var instance = Singleton()</pre><pre>private init(){}</pre><pre>public static func getInstance() -&gt; Singleton {</pre><pre>return instance</pre><pre>}</pre><pre>*/</pre><pre><strong>   public</strong> <strong>static</strong> <strong>var</strong> numberOfInstance : Int = 0</pre><pre><strong>   public</strong> <strong>static</strong> <strong>var</strong> maxNumberOfInstance : Int = 10</pre><pre><strong>   public</strong> <strong>static</strong> <strong>var</strong> money : Int = 1000</pre><pre><strong>   private</strong> <strong>init</strong>(){</pre><pre>     Hall.<strong>self</strong>.numberOfInstance = Hall.<strong>self</strong>.numberOfInstance + 1</pre><pre>   }</pre><pre><strong>   private</strong> <strong>static</strong> <strong>var</strong> helper : [AdminInstance] = [</pre><pre>     AdminInstance(),</pre><pre>     OnlyOneInstance(),</pre><pre>     LimitNumberOfInstance(),</pre><pre>     InstanceOfMoney()</pre><pre>   ]</pre><pre><strong>   public</strong> <strong>static</strong> <strong>func</strong> getInstance(condition: Int) -&gt; Hall? {</pre><pre><strong>     let</strong> ad : AdminInstance = helper[condition]</pre><pre><strong>     if</strong> ad.CanGetInstance() {</pre><pre><strong>       return</strong> Hall()</pre><pre>     }</pre><pre><strong>     return</strong> <strong>nil</strong></pre><pre>    }</pre><pre>}</pre><pre><strong>class</strong> AdminInstance {</pre><pre><strong>   public</strong> <strong>func</strong> CanGetInstance() -&gt; Bool {</pre><pre><strong>      return</strong> <strong>true</strong></pre><pre>   }</pre><pre>}</pre><pre><strong>class</strong> OnlyOneInstance : AdminInstance {</pre><pre><strong>   public</strong> <strong>override</strong> <strong>func</strong> CanGetInstance() -&gt; Bool {</pre><pre><strong>     if</strong> Hall.numberOfInstance &lt; 1 {</pre><pre><strong>       return</strong> <strong>true</strong></pre><pre>     }</pre><pre><strong>     return</strong> <strong>false</strong></pre><pre>   }</pre><pre>}</pre><pre><strong>class</strong> LimitNumberOfInstance : AdminInstance {</pre><pre><strong>    public</strong> <strong>override</strong> <strong>func</strong> CanGetInstance() -&gt; Bool {</pre><pre><strong>      if</strong> Hall.numberOfInstance &lt; Hall.maxNumberOfInstance {</pre><pre><strong>       return</strong> <strong>true</strong></pre><pre>      }</pre><pre><strong>      return</strong> <strong>false</strong></pre><pre>    }</pre><pre>}</pre><pre><strong>class</strong> InstanceOfMoney : AdminInstance {</pre><pre><strong>    public</strong> <strong>override</strong> <strong>func</strong> CanGetInstance() -&gt; Bool {</pre><pre><strong>      if</strong> Hall.money &gt;= 100 {</pre><pre><strong>       return</strong> <strong>true</strong></pre><pre>      }</pre><pre><strong>      return</strong> <strong>false</strong></pre><pre>   }</pre><pre>}</pre><pre><strong>let</strong> hall = Hall.getInstance(condition: 1) // 1 instance</pre><pre><strong>let</strong> hall2 = Hall.getInstance(condition: 2) // 2 instance</pre><p>Ngoài ra còn rất nhiều cách viết và khởi tạo đối tượng với Singleton tuỳ vào từng trường hợp cụ thể như Eager, Lazy, Double Check, Synchronize, Enum…., các bạn có thể tìm hiểu thêm</p><p>2. <strong>Delegate</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7SfL33HO8K3pATt_9CCGtg.png" /><figcaption>delegate</figcaption></figure><ul><li>Delegate là một design pattern thuộc nhóm <em>Behavior</em></li><li>Delegate chuyển giao việc thực hiện một số chức năng cho một lớp khác và thông báo khi có sự thay đổi để 2 lớp có thể làm việc với nhau</li><li>Delegate đảm bảo nguyên tắc Single Responsibility Principle: một lớp chỉ nên có một nhiệm vụ duy nhất khi tách rời phần xử lí một chức năng ra khỏi lớp ban đầu</li><li>Delegate đảm bảo nguyên tắc Open/Close Principle: khi mở rộng hành vi mà không ảnh hưởng đến ứng dụng</li><li>Được sử dụng để thay thế cho sự kế thừa</li></ul><p>Ví dụ: Một độc giả làm mất sách và chỉ nhớ tên và một vài thông tin khác của cuốn sách, ông ta nhờ Thư viên tìm giúp sách đó trong thư viện. Khi tìm xong thư viện sẽ thông báo lại cho ông ấy.</p><pre>// Cuốn sách ông ta làm mất </pre><pre><strong>struct</strong>  book {</pre><pre><strong>   var</strong> name : String?</pre><pre>}</pre><pre><br>// Người làm mất sách cùng thông tin sách bị mất </pre><pre><strong>class</strong> Readers {</pre><pre><strong>   var</strong> myName : String = &quot;isMe&quot;</pre><pre><strong>   var</strong> book : book?</pre><pre>}</pre><pre><br>// Thư viện nơi giúp ông ta tìm sách mới </pre><pre><strong>class</strong> Library {</pre><pre><strong>   weak</strong> <strong>var</strong> readers : LibraryProtocol?</pre><pre><strong>   func</strong> didFind(<strong>_</strong> book:book) {</pre><pre>     readers?.findMyBook(<strong>self</strong>, didFinishFind: book)</pre><pre>   }</pre><pre>}</pre><pre>// Định ra một cách thức tìm sách mới trong thư viện</pre><pre><strong>protocol</strong> LibraryProtocol : class {</pre><pre><strong>   func</strong> findMyBook(<strong>_</strong> library : Library, didFinishFind book: book)</pre><pre>}</pre><pre>// Sau khi tìm được sẽ liên lạc và thông báo lại cho độc giả </pre><pre><strong>extension</strong> Readers : LibraryProtocol {</pre><pre><strong>   func</strong> findMyBook(<strong>_</strong> library: Library, didFinishFind book: book) {</pre><pre><strong>     self</strong>.book = book<br>   }</pre><pre>}</pre><p>3. <strong>Chain of Responsibility</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*spEVmuSwVAoQB0DTMwNnMw.png" /><figcaption>ResponderChain</figcaption></figure><ul><li>Là một design pattern thuộc nhóm <em>Behavior</em></li><li>Kết nối các đối tượng thành một chuỗi Chain và gửi yêu cầu xử lí đến tất cả các đối tượng trong chuỗi đến khi có đối tượng chấp nhận xử lí đó</li><li>Chain of Responsibility sử dụng như danh sách liên kết với việc gửi yêu cầu đệ quy qua các node trong chuỗi</li><li>Chain of Responsibility giảm kết nối đến toàn bộ đối tượng trong hệ thống bằng việc kết nối đến 1 đối tượng tiếp theo</li><li>Đảm bảo nguyên tắc Single Responsibility Principle và Open/Close trong lập trình OOP</li></ul><pre>// Cung cấp handle và kết nối các handle lại với nhau thành chuỗi</pre><pre><strong>@objc</strong> <strong>protocol</strong> Handle : class {</pre><pre><strong>   var</strong> nextHandle : Handle? {<strong>get</strong> <strong>set</strong>}</pre><pre><strong>   @objc</strong> <strong>optional</strong> <strong>func</strong> setHandle(handle: Handle) -&gt; Handle</pre><pre><strong>   func</strong> handle(request : String ) -&gt; String?</pre><pre>}</pre><pre><br>// Cài đặt việc cài đặt và kiểm tra điều kiện khi gửi yêu cầu qua các handle trong chuỗi</pre><pre><strong>extension</strong> Handle {</pre><pre><strong>   func</strong> setHandle(handle: Handle) -&gt; Handle {</pre><pre><strong>     self</strong>.nextHandle = handle</pre><pre><strong>     return</strong> handle</pre><pre>   }</pre><pre><strong>   func</strong> handle(request : String ) -&gt; String {</pre><pre><strong>     return</strong> ((nextHandle?.handle(request: request))!)</pre><pre>   }</pre><pre>}</pre><pre><strong>class</strong> MonkeyHandle : Handle {</pre><pre>   <strong>var</strong> nextHandle: Handle?</pre><pre><strong>   func</strong> handle(request: String) -&gt; String? {</pre><pre><strong>   if</strong> request == &quot;Banana&quot; {</pre><pre><strong>     return</strong> &quot;Monkey eat \(request) \n&quot;</pre><pre>   }</pre><pre><strong>   else </strong>{</pre><pre><strong>     return</strong> nextHandle?.handle(request: request)</pre><pre>   }</pre><pre>}</pre><pre>}</pre><pre><strong>class</strong> DogHanle : Handle {</pre><pre><strong>   var</strong> nextHandle: Handle?</pre><pre><strong>   func</strong> handle(request: String) -&gt; String? {</pre><pre><strong>     if</strong> request == &quot;Bone&quot; {</pre><pre><strong>       return</strong> &quot;Dog eat \(request) \n&quot;</pre><pre>     }</pre><pre><strong>     else</strong> {</pre><pre><strong>       return</strong> nextHandle?.handle(request: request)</pre><pre>     }</pre><pre>   }</pre><pre>}</pre><pre><strong>class</strong> TigerHanle : Handle {</pre><pre><strong>   var</strong> nextHandle: Handle?</pre><pre><strong>   func</strong> handle(request: String) -&gt; String? {</pre><pre><strong>     if</strong> request == &quot;Meat&quot; {</pre><pre><strong>       return</strong> &quot;Tiger eat \(request) \n&quot;</pre><pre>     }</pre><pre><strong>     else </strong>{</pre><pre><strong>       return</strong> nextHandle?.handle(request: request)</pre><pre>     }</pre><pre>   }</pre><pre>}</pre><pre><strong>class</strong> Client {</pre><pre><strong>   static</strong> <strong>func</strong> SetUpHanlde(handle: Handle){</pre><pre><strong>     let</strong> food = [&quot;Bone&quot;, &quot;Banana&quot;, &quot;Meat&quot;]</pre><pre><strong>     for</strong> item <strong>in</strong> food {</pre><pre>       print(&quot;Who need \(item) ? \n&quot;)</pre><pre><strong>       guard</strong> <strong>let</strong> result = handle.handle(request: item) <strong>else</strong> {</pre><pre>         print(&quot;\(item) has left channel&quot;)</pre><pre><strong>         return</strong></pre><pre>       }</pre><pre>      print(result)</pre><pre>    }</pre><pre>  }</pre><pre>}</pre><pre><strong>func</strong> test() {</pre><pre><strong>   let</strong> monkey = MonkeyHandle()</pre><pre><strong>   let</strong> dog = DogHanle()</pre><pre><strong>   let</strong> tiger = TigerHanle()</pre><pre>   monkey.setHandle(handle: dog).setHandle?(handle: tiger)</pre><pre>   Client.SetUpHanlde(handle: monkey)</pre><pre>   Client.SetUpHanlde(handle: dog)</pre><pre>}</pre><pre>test()</pre><p>4. <strong>Observer</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_d-Oe_zYZq1rYapYgPMHmw.png" /><figcaption>Observer</figcaption></figure><ul><li>Observer là một design pattern thuộc nhóm <em>Behavior</em></li><li>Định nghĩa một mối quan hệ 1-n giữa các đối tượng, khi đó một đối tượng thay đổi trạng thái của mình nó sẽ thông báo đến tất cả các đối tượng khác có quan hệ với nó và chúng sẽ được cập nhật tự động. Observer có thể đăng kí/huỷ đăng kí với hệ thống mà nó tham gia</li><li>Đảm bảo nguyên tắc Open/Close principle trong lập trình hướng đối tượng khi mà Subject và Observer có thể thay đổi độc lập nhau</li></ul><pre><strong>protocol</strong> Observer{</pre><pre><strong>   func</strong> update(event: String)</pre><pre>}</pre><pre><strong>protocol</strong> Subject {</pre><pre><strong>   func</strong> attach(observer: Observer)</pre><pre><strong>   func</strong> detach(observer: Observer)</pre><pre><strong>   func</strong> notifyAll(event: String)</pre><pre>}</pre><pre><strong>class</strong> ConcreteObserver: Observer {</pre><pre><strong>   func</strong> update(event: String) {</pre><pre>     print(&quot;update event&quot;)</pre><pre>   }</pre><pre>}</pre><pre><strong>class</strong> ConcreteSubject : Subject {</pre><pre><strong>   var</strong> list = [Observer]()</pre><pre><strong>   func</strong> attach(observer: Observer) {</pre><pre>     list.append(observer)</pre><pre>   }</pre><pre><strong>   func</strong> detach(observer: Observer) {</pre><pre>     list.remove(at: list.count)</pre><pre>   }</pre><pre><strong>   func</strong> notifyAll(event: String) {</pre><pre><strong>     for</strong> item <strong>in</strong> list {</pre><pre>       item.update(event: event)</pre><pre>     }</pre><pre>   }</pre><pre>}</pre><pre>// Ví dụ cụ thể: User subcribe vào 1 group, đăng bài và thông báo đến các đối tượng khác trong group</pre><pre><strong><br>class</strong> User : Hashable {</pre><pre><strong>   var</strong> hashValue : Int = 0</pre><pre><strong>   var</strong> name : String</pre><pre><strong>   init</strong>(name: String ) {</pre><pre><strong>     self</strong>.name = name</pre><pre>   }</pre><pre><strong>   static</strong> <strong>func</strong> == (lhs: User, rhs: User) -&gt; Bool {</pre><pre><strong>     return</strong> lhs.hashValue == rhs.hashValue</pre><pre>   }</pre><pre><strong>   func</strong> notify(post: Post) {</pre><pre>     print(&quot;User: \(name) Content: \(String(describing: post.content))&quot;)</pre><pre>   }</pre><pre><strong>   func</strong> subcribe(group: FBGroup, topic: [String]) {</pre><pre>     group.Join(user: <strong>self</strong>, topic: topic)</pre><pre>   }</pre><pre><strong>   func</strong> Post(fbgroup: FBGroup, content: String, topic: [String]) {</pre><pre>     fbgroup.addPost(user: <strong>self</strong>, content: content, topic:       ChangeTopic(topic: topic))</pre><pre>   }</pre><pre><strong>   func</strong> ChangeTopic(topic: [String]) -&gt; [String: Int] {</pre><pre><strong>     var</strong> response = [String: Int]()</pre><pre><strong>     for</strong> i <strong>in</strong> 1...topic.count {</pre><pre>       response.updateValue(1, forKey: topic[i])</pre><pre>     }</pre><pre><strong>     return</strong> response</pre><pre>   }</pre><pre>}</pre><pre><strong>class</strong> FBGroup {</pre><pre><strong>   private</strong> <strong>var</strong> name : String?</pre><pre><strong>   var</strong> listPost = [Post]()</pre><pre><strong>   var</strong> listUser = [User : [String]]()</pre><pre><strong>   init</strong>(name: String) {</pre><pre><strong>     self</strong>.name = name</pre><pre>   }</pre><pre><strong>   func</strong> addPost(user: User, content: String, topic: [String:Int]) {</pre><pre><strong>     for</strong> user <strong>in</strong> listUser.keys {</pre><pre><strong>       if</strong> user == user {</pre><pre><strong>         let</strong> post : Post = Post(content: content, list: topic)</pre><pre>         NotifyAll(post: post)</pre><pre>         listPost.append(post)</pre><pre>       }</pre><pre>    }</pre><pre>  }</pre><pre><strong>    func</strong> UpdateTopicFromUser(user: User, newTopic: [String]) -&gt; Bool      {</pre><pre><strong>      for</strong> item  <strong>in</strong> listUser.keys {</pre><pre><strong>        if</strong> item == user {</pre><pre>          listUser.updateValue(newTopic, forKey: user)</pre><pre><strong>            return</strong> <strong>true</strong></pre><pre>        }</pre><pre>      }</pre><pre><strong>    return</strong> <strong>false</strong></pre><pre>   }</pre><pre><strong>   func</strong> Join(user: User, topic: [String])  {</pre><pre>     listUser.updateValue(topic, forKey: user)</pre><pre>   }</pre><pre><strong>   func</strong> NotifyAll(post: Post) {</pre><pre><strong>     for</strong> user <strong>in</strong> listUser.keys {</pre><pre>       user.notify(post: post)</pre><pre>     }</pre><pre>   }</pre><pre>}</pre><pre><strong>class</strong> Post {</pre><pre><strong>   var</strong> content : String?</pre><pre><strong>   var</strong> list = [String:Int]() </pre><pre><strong>   init</strong>(content: String, list: [String:Int]) {</pre><pre><strong>     self</strong>.content = content</pre><pre><strong>     self</strong>.list = list</pre><pre>   }</pre><pre>}</pre><pre><strong>func</strong> test() {</pre><pre><strong>   let</strong> gr1 = FBGroup(name: &quot;1&quot;)</pre><pre><strong>   let</strong> gr2 = FBGroup(name: &quot;2&quot;)</pre><pre><strong>   let</strong> u1 = User(name: &quot;user1&quot;)</pre><pre><strong>   let</strong> u2 = User(name: &quot;user2&quot;)</pre><pre><strong>   let</strong> u3 = User(name: &quot;user3&quot;)</pre><pre>   u1.subcribe(group: gr1, topic: [&quot;topic1&quot;, &quot;topic2&quot;])</pre><pre>   u2.subcribe(group: gr2, topic: [&quot;topic3&quot;, &quot;topic4&quot;])</pre><pre>   u3.subcribe(group: gr2, topic: [&quot;topic5&quot;, &quot;topic6&quot;])</pre><pre>   u1.subcribe(group: gr2, topic: [&quot;topic7&quot;, &quot;topic8&quot;])</pre><pre>   u1.Post(fbgroup: gr2, content: &quot;content1&quot;, topic: [&quot;newtopic1&quot;,&quot;newtopic2&quot;])</pre><pre>}</pre><pre>test()</pre><p>Bên trên là một vài design pattern cơ sở để có thể hiểu thêm về mô hình VIPER!</p><p>Nếu có gì sai sót, mong mọi người để lại comment để mình chỉnh sửa và rút kinh nghiệm!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb15edfc071f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is GCD?]]></title>
            <link>https://medium.com/@thnhtoi/what-is-gcd-31ffbd940227?source=rss-f45a72911603------2</link>
            <guid isPermaLink="false">https://medium.com/p/31ffbd940227</guid>
            <category><![CDATA[grand-central-dispatch]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Thành Toại]]></dc:creator>
            <pubDate>Thu, 12 Dec 2019 14:47:20 GMT</pubDate>
            <atom:updated>2019-12-13T04:55:30.367Z</atom:updated>
            <content:encoded><![CDATA[<ol><li><strong>Khái niệm:</strong></li></ol><p>“<em>Grand Central Dispatch (GCD) is a </em><strong><em>low-level</em></strong><em> API for managing concurrent operations</em>”</p><p>Có thể hiểu rằng:</p><ul><li>Là những API ở mức <em>low-level</em></li><li>Làm cho ứng dụng chạy tốt hơn</li><li>Hỗ trợ nhiều task chạy cùng lúc</li><li>Tối ưu khi làm việc với Mutil-Threading</li></ul><p><strong>Thread</strong>: khi bạn khởi chạy một chương trình, sẽ có một Process(tiến trình) do hệ điều hành cung cấp quản lí chương trình đó, trong Process đó sẽ chứa một hoặc nhiều tiểu trình điều khiển Process và những tác vụ liên quan, những tiểu trình đó được gọi là Thread. Trong một Process sẽ có một Thread chính(Main-Thread) và nhiều Thread khác chạy đồng thời và chia sẻ chung giữ liệu với nhau để xử lí!. Việc có nhiều Thread trong một Process giúp tăng hiệu xuất của chương trình, giúp chương trình làm được nhiều công việc hơn, giảm tải khi chỉ có một Main-Thread đảm nhiệm toàn bộ Process. Một vài đặc điểm của Thread trong Swift:</p><ul><li>Chỉ có Main-Thread mới có thể cập nhật UI(User Interface).</li><li>Mọi hoạt động cập nhập UI phải thông qua Main-Thread nếu không chương trình sẽ bị crash.</li><li>Thuộc mức <em>low-level </em>trong hệ thống<em> </em>nên gây khó khăn trong việc sử lí các công việc đồng thời</li><li>Các vấn đề về pause/resume hoặc sử lí đồng bộ/bất đồng bộ gặp nhiều khó khăn.</li></ul><p><strong>Concurrency vs Parallelism:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*gTpK25yWejnGWPxOWtaqRg.png" /></figure><ul><li>Concurrency: là một thuộc tính của chương trình, khiến mọi thứ xảy ra cùng thời điểm. Nó là việc tạo ra một Thread trong quá trình xử lí nhưng việc quản lí các Thread không phải là điều đơn giản.</li><li>Parallelism: khiến mọi thứ diễn ra song song, là một thuộc tính của máy</li></ul><p><strong>Giải pháp</strong>: thay vì tạo ra các Thread thì chỉ cần xác định các công việc cần thực hiện để thực hiện chúng. GCD ra đời và hỗ trợ các vấn đề này.</p><p><em>“Basically, </em><strong><em>concurrency</em></strong><em> is about </em><strong><em>structure</em></strong><em> while </em><strong><em>parallelism</em></strong><em> is about </em><strong><em>execution</em></strong><em>.”</em></p><p>2. <strong>GCD có thể giải quyết những vấn đề gì?</strong></p><p>“<em>Note that GCD decides how much parallelism it requires based on the system and available system resources. It’s important to note that parallelism </em><strong><em>requires</em></strong><em> concurrency, but concurrency does not </em><strong><em>guarantee</em></strong><em> parallelism</em>”</p><ul><li>Đơn giản để thêm 1 Thread</li><li>Chỉ cần xác định các công việc và thêm chúng vào <strong>Queue. </strong>Các queue sẽ chứa các tasks và chúng ta sẽ thao tác với tasks còn việc điều phối Thread sẽ do GCD đảm nhiệm</li><li>Mọi handle thread được thực hiện tự động</li><li>Đơn giản để xử lí đồng bộ/bất đồng bộ</li></ul><p>3. <strong>Dispatch Queue</strong></p><p>Hoạt động theo cơ chế FIFO, giúp quản lí các tasks được thêm vào, nó là một Thread-safe đảm bảo và có thể truy cập từ bất cứ đâu. Có 2 loại dispatch queue là: serial queue và concurrent queue</p><p><strong>Serial Queue</strong>: các task được thực hiện theo thứ tự. Task khác chỉ có thể thực hiện khi task trước đó đã thực hiện xong. Tuy nhiên ta vẫn có thể chạy những task đồng thời bằng việc sử dụng nhiều serial queue.</p><p><strong>Concurrent queue</strong>: cho phép các task có thể thực hiện đồng thời nhưng không quyết định được sự kết thúc của một task</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kLTpCjo0IVcEmrIIyEoBgg.png" /></figure><p>GCD cung cấp 3 loại queue chính là: Main queue, Global queues và Custom queue.</p><p><strong>Main queue:</strong></p><ul><li>Là một serial queue</li><li>Thực hiện trên Main-Thread</li></ul><p><strong>Global queue:</strong></p><ul><li>Là một concurrent queue</li><li>Chạy trên toàn bộ hệ thống</li><li>Có 4 loại QoS với mức độ ưu tiên giảm dần: High, Default, Low và Background</li></ul><p><strong>Custom queue:</strong></p><ul><li>Có thể là serial queue hoặc concurrent queue tuỳ theo người cấu hình</li></ul><p>Ví dụ:</p><pre>// main queue<br>DispatchQueue.main.async {</pre><pre><strong>    for</strong> i <strong>in</strong> 1...5 {</pre><pre>    print(i)</pre><pre>   }</pre><pre>}</pre><pre>// global queue<br>DispatchQueue.global().async {</pre><pre><strong>    for</strong> i <strong>in</strong> 1...5 {</pre><pre>    print(i)</pre><pre>  }</pre><pre>}</pre><pre>// custom queue<br><strong>let</strong> customQueue = DispatchQueue(label: &quot;fx.xy.custom&quot;, qos: .userInitiated)</pre><pre>customQueue.sync {</pre><pre><strong>    for</strong> i <strong>in</strong> 1...5{</pre><pre>    print(i)</pre><pre> }</pre><pre>}</pre><p>Ở ví dụ trên ta có sử dụng sync/async. Để hiểu rõ hơn ta qua phần mới thoi :))</p><p>3. <strong>Synchronous vs Asynchronous</strong></p><p>Lại ví dụ:</p><pre><strong>let</strong> queues = DispatchQueue(label: &quot;fx.xy.custom&quot;)</pre><pre>   queues.sync {</pre><pre><strong>   for</strong> i <strong>in</strong> 1...5 {</pre><pre>     print(i)</pre><pre>   }</pre><pre>}</pre><pre>for i in 100...105 {</pre><pre>   print(i)</pre><pre>}</pre><pre>// out put <br>1 2 3 4 5 100 101 102 103 104 105</pre><pre><strong>let</strong> queues = DispatchQueue(label: &quot;fx.xy.custom&quot;)</pre><pre>queues.async {</pre><pre><strong>   for</strong> i <strong>in</strong> 1...5 {</pre><pre>    print(i)</pre><pre>  }</pre><pre>}</pre><pre>for i in 100...105 {</pre><pre>    print(i)</pre><pre>}</pre><pre>// out put <br>1 100 2 101 3 102 103 104 4 5 105 </pre><p>Khi ta sử dụng sync các lệnh in được thực hiện theo đúng thứ tự và tuần tự nhau. Đối với async thì khác, thứ tự các phần tử in vẫn đúng theo thứ tự nhưng được xắp xếp lộn xộn giữa 2 phần.</p><p>4. <strong>Chi tiết</strong></p><p>Việc sử dụng nhiều serial queue sẽ dẫn tới tài nguyên cấp phát quá nhiều từ hệ thống, để các công việc sử lí đồng thời trong cùng một queue thì việc sử dụng Concurrent queue là giải pháp.</p><p>Thêm một tham số vào hàm tạo queue để thay đổi attributes mặc định(serial) thành concurrent queue.</p><pre><strong>let</strong> queues = DispatchQueue(label: &quot;fx.xy.custom&quot;, qos: .utility, attributes: .concurrent)</pre><pre>   queues.async {</pre><pre><strong>   for</strong> i <strong>in</strong> 1...5 {</pre><pre>     print(i)</pre><pre>   }</pre><pre>}</pre><pre>queues.async {</pre><pre><strong>   for</strong> i <strong>in</strong> 100...105 {</pre><pre>     print(i)</pre><pre>   }</pre><pre>}</pre><p>Đôi lúc ta muốn quyết định sự bắt đầu của một queue để các task được thêm vào không thực thi ngay lập tức. Ta thay đổi thuộc tính của attributes thành initiallyInactive và sử dụng <a href="https://developer.apple.com/documentation/dispatch/dispatchobject/1641002-activate">activate()</a> để bắt đầu queue</p><pre><strong>let</strong> queues = DispatchQueue(label: &quot;fx.xy.custom&quot;, qos: .utility, attributes: .initiallyInactive)</pre><pre>   queues.async {</pre><pre><strong>   for</strong> i <strong>in</strong> 1...5 {</pre><pre>  print(i) </pre><pre> }</pre><pre>}</pre><pre>queues.async {</pre><pre><strong>   for</strong> i <strong>in</strong> 100...105 {</pre><pre>     print(i)</pre><pre>   }</pre><pre>}</pre><pre>queues.activate()</pre><pre>print(&quot;Do something 1&quot;)</pre><pre>print(&quot;Do something 2&quot;)</pre><pre>queues.activate()</pre><pre>print(&quot;Do something 3&quot;)</pre><p>Tuy nhiên, queue trên thực thi theo kiểu serial. Vậy để có thể điều khiển queue chạy theo ý mình vừa sử dụng concurrent queue ta sử dụng một mảng chứa cả initiallyInactive và concurrent.</p><pre><strong>let</strong> queues = DispatchQueue(label: &quot;fx.xy.custom&quot;, qos: .utility, attributes: [.concurrent, .initiallyInactive])</pre><pre>queues.async {</pre><pre><strong>   for</strong> i <strong>in</strong> 1...5 {</pre><pre>     print(i)  </pre><pre>   }</pre><pre>}</pre><pre>queues.async {</pre><pre><strong>   for</strong> i <strong>in</strong> 100...105 {</pre><pre>     print(i)</pre><pre>   }</pre><pre>}</pre><pre>queues.activate()</pre><pre>print(&quot;Do something 1&quot;)</pre><pre>print(&quot;Do something 2&quot;)</pre><pre>queues.activate()</pre><pre>print(&quot;Do something 3&quot;)</pre><p>Khi điều khiển được một queue bắt đầu, ta lại muốn nó dừng lại và thực hiện một vài công việc trong một block code ở một khoảng thời gian cho trước. Giải pháp ở đây là <a href="https://developer.apple.com/documentation/dispatch/dispatchqueue/2300020-asyncafter">asyncAfter(deadline:execute:)</a>.</p><ul><li>Deadline: là một <a href="https://developer.apple.com/documentation/dispatch/dispatchtime">DispatchTime</a> quy định khoảng thời gian mong muốn. Sử dụng .now() là thời điểm thực thi</li><li>Execute: là một <a href="https://developer.apple.com/documentation/dispatch/dispatchworkitem">DispatchWorkItem</a> chứa danh sách các công việc thực hiện.</li></ul><pre><strong>let</strong> queues = DispatchQueue(label: &quot;fx.xy.custom&quot;, qos: .utility)</pre><pre>queues.async {</pre><pre>   print(&quot;Hello&quot;)</pre><pre>}</pre><pre><strong>let</strong> delayTime : DispatchTimeInterval = .seconds(5)</pre><pre>queues.asyncAfter(deadline: .now() + delayTime){</pre><pre>   print(&quot;Toai&quot;)</pre><pre>}</pre><p>Lệnh in “Toai” sẽ được thực thi sau 5s kể từ khi lệnh in “Hello”</p><p>Ngoài các cách kể trên, bạn có thể sử dụng DispatchQueue.global() để khởi tạo nhanh một queue mà không cần phải truyền quá nhiều tham số ngoài mức độ ưu tiên mong muốn. Việc sử dụng các tính năng như delay… là hoàn toàn giống nhau.</p><p>5. <strong>DispatchWorkItem</strong></p><p>“<em>The work you want to perform, encapsulated in a way that lets you attach a completion handle or execution dependencies</em>.”</p><ul><li>Định nghĩa các công việc muốn thực hiện</li><li>Là một block code</li><li>Có thể thêm vào các queue và thực hiện trên cả Main-Thread, Background hoặc Thread.</li><li>Đơn giản hơn trong việc quản lí Thread</li><li>Tách thành các đơn vị nhỏ, dễ quản lí</li></ul><pre><strong>let</strong> workItem = DispatchWorkItem {</pre><pre>    // do something</pre><pre>}</pre><ul><li>Để thực thi thì ta dùng lệnh <a href="https://developer.apple.com/documentation/dispatch/dispatchworkitem/1781026-perform">perform()</a></li><li>Khi không ở trong một Thread nào thì thực thi ở Main-Thread</li><li>Khi một workItem làm việc có thể thông báo cho các Thread khác hoặc Main-Thread bằng hàm <a href="https://developer.apple.com/documentation/dispatch/dispatchworkitem/1781021-notify">notify(queue: DispatchQueue, execute: DispatchWorkItem)</a></li><li>Khi muốn đợi một công việc để thực hiện: <a href="https://developer.apple.com/documentation/dispatch/dispatchworkitem/2016075-wait">wait(timeout: DispatchTime)</a></li><li>Huỷ bỏ một công việc: <a href="https://developer.apple.com/documentation/dispatch/dispatchworkitem/1780910-cancel">cancel()</a></li></ul><pre><strong>var</strong> value = 5</pre><pre><strong>let</strong> workItem = DispatchWorkItem{</pre><pre>    value = value + 5</pre><pre>}</pre><pre>workItem.perform()</pre><pre>print(value)</pre><pre><strong>let</strong> queues = DispatchQueue.global()</pre><pre>queues.async(execute: workItem)</pre><pre>workItem.notify(queue: DispatchQueue.main){</pre><pre>print(value)</pre><pre>}</pre><pre>workItem.cancel()</pre><p>6. <strong>DispatchGroup</strong></p><p>“<em>A group of tasks that you monitor as a single unit.</em>”</p><ul><li>Nhóm các task cần thực hiện lại kể cả đồng bộ và bất đồng bộ</li><li>Quản lí việc thực thi các task</li><li>Chủ động việc chờ đợi và hoàn thành</li><li>Giảm thiểu tài nguyên cần xử lí</li></ul><pre>DispatchQueue.global(qos: .utility).async {</pre><pre><strong>let</strong> dispatchGroup = DispatchGroup()</pre><pre>dispatchGroup.enter()</pre><pre>task1 {</pre><pre>   // do something</pre><pre>   dispatchGroup.leave()</pre><pre>}</pre><pre>dispatchGroup.enter()</pre><pre>task2 {</pre><pre>   // do something</pre><pre>   dispatchGroup.leave()</pre><pre>}</pre><pre>dispatchGroup.wait()</pre><pre>dispatchGroup.notify(queue: .main){</pre><pre>   print(&quot;ok&quot;)</pre><pre>  }</pre><pre>}</pre><p>Khi đưa một task vào group thì cần enter() và leave() đúng với số lần đưa vào, nếu không chương trình sẽ chạy không kết thúc. Có thể sử dụng wait() để dừng toàn bộ Thread lại và chờ các task thực thi xong và thông báo cho các Thread khác.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31ffbd940227" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Programing in Swift]]></title>
            <link>https://medium.com/@thnhtoi/functional-programing-in-swift-e39ee0ee2b82?source=rss-f45a72911603------2</link>
            <guid isPermaLink="false">https://medium.com/p/e39ee0ee2b82</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Thành Toại]]></dc:creator>
            <pubDate>Mon, 09 Dec 2019 02:49:35 GMT</pubDate>
            <atom:updated>2019-12-13T07:43:23.058Z</atom:updated>
            <content:encoded><![CDATA[<ol><li><strong>Cơ bản về Functional Programing</strong></li></ol><p>Theo Wikipedia:</p><p>“<em>“Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data”. In other words, functional programming promotes code with no side effects, no change of value in variables. It oposes to imperative programming, which emphasizes change of state”.</em></p><p>Trong khoa học máy tính lập trình chức năng là một mô hình lập trình-một phong cách xây dựng cấu trúc cùng các yếu tố của chương trình máy tính-xem việc tính toán là đánh giá các chức năng toán học và tránh việc thay đổi giữ liệu và có thể thay đổi. Tuy nhiên, có thể hiểu rằng Functional Programing là việc giải quyết một vấn đề bằng cách chia nhỏ thành các function khác nhau. Trong mỗi function có thể chứa các function khác làm input hoặc output cho chính nó. Như đã nói ở trên, trong quá trình liên kết các function lại với nhau chúng ta hạn chế việc thay đổi các trạng thái cũng như không quy định rõ thứ tự của các function</p><p>2. <strong>Lợi ích của việc lập trình chức năng?</strong></p><p><strong>Code rõ ràng và lành mạch</strong>: các biến không được sửa đổi khi đã xác định trong hàm vì vậy chúng ta có thể bỏ qua việc theo dõi sự thay đổi trạng thái của hàm, phương thức, lớp.. trong quá trình hoạt động. Nếu chúng ta gọi một hàm có cùng tham số, kết quả là giống nhau bất kể bạn gọi hàm bao nhiêu lần(không có trạng thái nào có thể thay đổi nó)</p><p><strong>Mô-đun hoá</strong>: Không có một state nào bao bọc toàn bộ chương trình, tách thành các thành phần nhỏ và liên kết chúng lại với nhau</p><p><strong>Đơn giản trong việc sửa lỗi</strong>: Các hàm là tách biệt với nhau, chỉ phụ thuộc vào đầu vào và đầu ra của chính hàm đó, vì thế việc lần ra lỗi và sửa chúng đơn giản hơn</p><p>Giảm thiểu tối đa lượng mã nguồn không thuần khiết và tách biệt chúng ra khỏi phần còn lại của chương trình</p><p>3. <strong>Tìm hiểu các Functions trong Swift?</strong></p><p><strong>Pure Function</strong>: Chỉ thao tác trên những tham số được truyền vào, không thay đổi biến, nhận vào input và trả ra output. Không thay đổi state và không tạo ra side-effects. Nó đơn giản là một hàm bình thường có thể có hoặc không có đối số đầu vào. Output tương tự nhau với cùng một input mà không quan tâm đến số lần chạy. Một pure Function hữu ích phải có tối thiểu một đối số đầu vào. Khi không nhận bất kì đối số nào mà chỉ trả về một chuỗi hay một giá trị nào đó thì ta nên khai báo chúng là một biết constant thay vì sử dụng function. Ví dụ:</p><pre>func toString() -&gt; String {<br>    return &quot;something&quot;<br>}</pre><pre>-&gt; let strString = &quot;something&quot; </pre><p><strong>Higher Order Functions</strong>: HOF là một function nhận vào một hoặc nhiều function như là tham số hoặc/và trả về kết quả là một function</p><pre>typealias sayHello = (String, String) -&gt; String</pre><pre>func caller(call: sayHello) -&gt; Void {    <br>    let result = call(&quot;Hello&quot;, &quot;Toai&quot;)<br>    print(result)<br>}</pre><pre>caller(call: { $0 + &quot; &quot; + $1 })</pre><p><strong>Map</strong></p><pre>let names = [&quot;milu&quot;, &quot;rantanplan&quot;]<br>let namesInUppercase = names.map { <br>    $0.uppercased() <br>}</pre><pre>print(namesInUppercase) //[&quot;MILU&quot;, &quot;RANTANPLAN&quot;]</pre><p><strong>Filter</strong></p><pre>let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]<br>let oddNumbers = numbers.filter <br>{ <br>    $0 % 2 != 0 <br>}</pre><pre>print(oddNumbers) //[1, 3, 5, 9]</pre><p><strong>Reduce</strong></p><pre>let numbers = [1, 2, 3, 4, 5]<br>let total = numbers.reduce(0, +)</pre><pre>print(total) //15</pre><p><strong>Closure</strong></p><pre>func add_x(_ x: Int) -&gt; ((Int) -&gt; Int) <br>{    <br>     func add_y(_ y: Int) -&gt; Int {        <br>     return x + y    <br>    }    <br>  return add_y<br>}</pre><pre>let add_5 = add_x(5)<br>let add_7 = add_x(7)</pre><pre>print(add_5(10))<br>// result 15</pre><pre>print(add_7(10)) <br>// result 17</pre><pre>print(add_x(2)(3))<br>// result 5</pre><p><strong>Currying và Partial Functions: </strong>Currying là một kĩ thuật cho phép chuyển đổi một function với nhiều tham số thành những function liên tiếp chỉ có một tham số. Ví dụ: func(a,b,c) chuyển thành g(a,b)h(c) hoặc g(a)h(b,c) hoặc đổi thứ tự của các function. Currying là một trường hợp của HOF vì nó trả về kết quả là một function.</p><pre>func sum(_ x: Int, _ y: Int) -&gt; Int {</pre><pre>  return x+y</pre><pre>}</pre><pre>func sumInSum(_ x: Int) -&gt; ((Int) -&gt; Int ) {</pre><pre>     func Sum(_ y: Int) -&gt; Int {</pre><pre>       return sum(x,y)</pre><pre>}</pre><pre>  return Sum</pre><pre>}</pre><pre>let plus = sumInSum(1)</pre><pre>print(plus(10)) <br>// output 11</pre><p><strong>4. Eager vs Lazy Evaluation</strong></p><p>Evaluation strategy:</p><p>“<em>A programing language uses an evaluation strategy to determine two things — </em><strong><em>when</em></strong><em> to evaluate the arguments of a function call(for function, also read: opertator, method, or relation) and </em><strong><em>what</em></strong><em> kind of value to pass to the function.</em>”</p><p><strong>What-</strong>kiểu giá trị nào được truyền cho hàm thì có 2 loại chính là call-by-value(String, Int, Double,Enum…) và call-by-reference(Class). Khi thao tác với call-by-value thì trong thân hàm chỉ làm việc với bản sao của đối số truyền vào nên không ảnh hưởng đến giá trị bên ngoài. Đối với call-by-reference thì ngược lại, mọi thay đổi bên trong thân hàm đều ảnh hưởng tới giá trị bên ngoài do chúng ta thao tác với một reference tới instance của đối số.</p><p><strong>When</strong>-khi nào đối số được evaluate thì có 3 loại chính. Bài viết này tập trung vào Eager evaluation còn 2 loại còn lại là Call by name và Call by need bạn có thể tìm hiểu vào bài viết sau.</p><p><strong>Eager Evaluation</strong>: các biểu thức được tính tại thời điểm các biến được xác định, hàm được gọi… Ví dụ:</p><pre><strong>func</strong> doSomething() -&gt; Bool {</pre><pre>   print(&quot;doSomething&quot;)</pre><pre><strong>   return</strong> <strong>true</strong></pre><pre>}</pre><pre><strong>func</strong> callDoSomeThing(something: Bool, call: String ) -&gt; Void {</pre><pre>   print(&quot;called&quot;)</pre><pre>}</pre><pre>callDoSomeThing(something: doSomething(), call: &quot;ok&quot;)</pre><pre>// output</pre><pre>doSomething</pre><pre>called</pre><p>Qua ví dụ ta thấy rằng hàm doSomething() được thực hiện trước khi hàm callDoSomething() được gọi. Đây là Eager Evaluation: đối số được evaluate trước khi truyền vào hàm</p><p><strong>Lazy evaluation: </strong>trì hoãn việc evaluate cho đến khi cần thiết.</p><p><strong>Call-by-name</strong>:</p><pre><strong>func</strong> doSomething() -&gt; Bool {</pre><pre>   print(&quot;doSomething&quot;)</pre><pre><strong>   return</strong> <strong>true</strong></pre><pre>}</pre><pre><strong>func</strong> callDoSomeThing(something: <strong>@autoclosure</strong> () -&gt; Bool, call: String ){</pre><pre>   print(&quot;called&quot;)</pre><pre><strong>   let</strong> test = call == &quot;200&quot; ? something() : <strong>false</strong></pre><pre>   print(&quot;result: \(test)&quot;)</pre><pre>}</pre><pre>callDoSomeThing(something: doSomething(), call: &quot;400&quot;)</pre><pre>// out put<br>called<br>result: false</pre><p>Ta đổi đối số của something thành closure. Khi cần ta sẽ gọi closure something() để evaluate. Như vậy đối số something sẽ không bị evaluate trước khi hàm callDosomeThing() được gọi. Ngoài trường hợp call: “200” thì đối số something() mới bị evaluate và thực thi hàm doSomething().</p><p><strong>Call-by-need</strong>: Cũng giống như call-by-name, call-by-need chỉ evaluate khi cần thiết và chỉ evaluate cho lần đầu tiên sau đó lưu lại để sử dụng cho những lần sau.</p><pre><strong>class</strong> Fx {</pre><pre><strong>    lazy</strong> <strong>var</strong> tx : Int = { [<strong>unowned</strong> <strong>self</strong>] <strong>in</strong></pre><pre>      print(&quot;call&quot;)</pre><pre><strong>      return</strong> 1</pre><pre>   }()</pre><pre>}</pre><pre>print(&quot;1&quot;)</pre><pre><strong>var</strong> x = Fx()</pre><pre>x.tx</pre><pre>print(&quot;2&quot;)</pre><pre>x.tx</pre><pre>// out put<br>1<br>call<br>2</pre><p>Lệnh call chỉ được tạo và in ra trong lần đầu tiên ta gọi hàm. Từ khoá lazy chỉ sử dụng với biến var vì giá trị của nó không được sử dụng khi quá trình evaluate hoàn tất. Đối với biến constant giá trị của nó luôn được gán trước quá trình evaluate nên không thể khởi tạo với lazy.</p><p><strong>Lợi ích</strong>: không có bộ nhớ tạm để lưu trữ các cấu trúc hoàn chỉnh, CPU không cần tính toán kết quả khi trả về. Swift hỗ trợ lazy properties và lazy collections.</p><p><strong>Một vài ngôn ngữ hỗ trợ Functional Programing</strong>:</p><ul><li>Haskell</li><li>ML (Standard ML, Objective Caml, …)</li><li>Scheme</li><li>Erlang</li><li>Scala</li><li>Closure</li><li>F#</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e39ee0ee2b82" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>