<?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 Muhammad Arif Rohman Hakim on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Arif Rohman Hakim on Medium]]></description>
        <link>https://medium.com/@rohmanhakim?source=rss-ee3cbad5a4bf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*11sxk2Q0Ez5T1xJ2MjgeHg.jpeg</url>
            <title>Stories by Muhammad Arif Rohman Hakim on Medium</title>
            <link>https://medium.com/@rohmanhakim?source=rss-ee3cbad5a4bf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 23:51:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rohmanhakim/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[Designing Error Returns in Go: A Case Study in Domain-Orchestration Separation]]></title>
            <link>https://medium.com/@rohmanhakim/designing-error-returns-in-go-a-case-study-in-domain-orchestration-separation-260009a5c662?source=rss-ee3cbad5a4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/260009a5c662</guid>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Muhammad Arif Rohman Hakim]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 07:04:40 GMT</pubDate>
            <atom:updated>2026-02-08T07:04:40.794Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YjjTh6GwS1lQRdStTGFGSw.png" /></figure><p>I recently refactored a Go codebase where I had a checking function isRepairable() that returns a boolean. Inside, it has several sequential checks with an early return pattern to validate against business rules:</p><pre>func isRepairable(doc *html.Node) bool {<br>    // Check 1: Competing roots<br>    if hasCompetingDocumentRoots(docQuery) {<br>        return false  <br>    }<br>    <br>    // Check 2: No structural anchors<br>    if len(headings) == 0 &amp;&amp; !hasStructuralAnchors(docQuery) {<br>        return false<br>    }<br>    <br>    // ... more checks ...<br>    <br>    // All checks passed - document is repairable<br>    return true<br>}</pre><p>The caller checks the returned bool and returns an error if it’s false:</p><pre>repairable := isRepairable(doc)<br>if !repairable {<br>    return SanitizedDoc{}, &amp;SanitizationError{<br>        Cause: ErrCauseStructurallyIncorrect,<br>        ...<br>    }<br>}</pre><p>The problem is every check always returns ErrCauseStructurallyIncorrect. It’s not wrong, it’s just very limiting. I wanted to make the error more granular for logging purposes, so the logging would be richer as I passed more context about the actual cause.</p><h3>The Observability Requirement</h3><p>At the highest level of the sanitization pipeline, there is observability logging:</p><pre>func (s *Sanitizer) Sanitize(<br>    inputDoc *html.Node,<br>) (SanitizedDoc, failure.ClassifiedError) {<br>    sanitizedDoc, err := sanitize(inputDoc)<br>    if err != nil {<br>        var sanitizationError *SanitizationError<br>        errors.As(err, &amp;sanitizationError)<br><br>        // Build contextual attributes based on the error cause<br>        attrs := buildErrorAttributes(sanitizationError)<br><br>        s.metadataRecorder.RecordError(<br>            time.Now(),<br>            &quot;sanitizer&quot;,<br>            &quot;Sanitizer.Sanitize&quot;,<br>            mapSanitizationErrorToMetadataCause(*sanitizationError),<br>            err.Error(),<br>            attrs,<br>        )<br>        return SanitizedDoc{}, sanitizationError<br>    }<br>    return sanitizedDoc, nil<br>}</pre><p>The sanitize() function calls isRepairable and uses its result to gatekeep the downstream sanitization process. I need granular error causes because RecordError() uses these to build metrics, alerts, and debugging context. This requirement constrained the design.</p><h3>Design Alternatives Considered</h3><p>There are several common patterns in Go for this type of function. Let me walk through what I considered and why I made the choices I did.</p><h4>Option 1: Return (bool, error)</h4><pre>func isRepairable(doc *html.Node) (bool, error) {<br>    // Check 1: Competing roots<br>    if hasCompetingDocumentRoots(doc) {<br>        return false, &amp;SanitizationError{<br>            Cause: ErrCauseCompetingRoots,<br>            ...<br>        }<br>    }<br>    <br>    // Check 2: No structural anchors<br>    if len(headings) == 0 &amp;&amp; !hasStructuralAnchors(doc) {<br>        return false, &amp;SanitizationError{<br>            Cause: ErrCauseNoStructuralAnchor,<br>            ...<br>        }<br>    }<br>    <br>    // ... more checks ...<br>    <br>    // All checks passed - document is repairable<br>    return true, nil<br>}</pre><p>You might ask:</p><blockquote><em>“What’s the purpose of the bool if you can just infer it from whether error is nil?”</em></blockquote><p><strong>Short answer:</strong> In (bool, error), the bool represents the domain truth of the predicate, while the error represents failure to evaluate or exceptional cause. They answer two different questions:</p><ul><li>bool -&gt; “Is the condition true?”</li><li>error -&gt; “Was the check itself successful?”</li></ul><p>This separation is intentional in Go API design.</p><p><strong>Long answer:</strong> A checker with (bool, error) distinguishes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*jye2sgSJahLPO5Mkjcw60A.png" /></figure><p>That gives three meaningful states:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*f8b3RY9C9TgOpkOOjDi4gg.png" /></figure><p>This is impossible to encode with just error unless you overload error to also mean “false,” which is often semantically wrong.</p><h4>When (bool, error) is genuinely useful:</h4><p><strong>1. False is a normal, non-error outcome</strong></p><p>Example: authorization check with infrastructure dependency.</p><pre>func IsAllowed(user User, resource string) (bool, error)</pre><ul><li>User not allowed -&gt; (false, nil) -&gt; normal business result</li><li>Policy service unreachable -&gt; (false, err) -&gt; operational failure</li></ul><p>Caller:</p><pre>ok, err := IsAllowed(u, r)<br>if err != nil {<br>    return err // system problem<br>}<br>if !ok {<br>    return ErrForbidden // domain result<br>}</pre><p>Without the bool, you’d be forced to treat “not allowed” as an error, which pollutes error semantics.</p><p><strong>2. To avoid using errors for control flow</strong></p><p>Go style discourages using errors to represent expected boolean outcomes. In Go, error is intended to signal abnormal or exceptional conditions, not ordinary branch outcomes. Using errors to encode expected boolean results conflates two semantic layers and degrades API clarity, performance, and composability.</p><p>Bad design:</p><pre>func CheckQuota(u User) error</pre><p>Where:</p><ul><li>nil = allowed</li><li>ErrQuotaExceeded = false</li></ul><p>This is acceptable for validation, but not ideal if false is a frequent, expected branch in normal flow. Then (bool, error) is clearer.</p><h4>Option 2: Return only error</h4><p>When false is the frequent case, it’s good to omit the bool and return only error. If it’s nil, the check passes.</p><pre>func validateRepairability(doc *html.Node) error {<br>    // Check 1: Competing roots<br>    if hasCompetingDocumentRoots(doc) {<br>        return &amp;SanitizationError{<br>            Cause: ErrCauseCompetingRoots,<br>            ...<br>        }<br>    }<br>    <br>    // Check 2: No structural anchors<br>    if len(headings) == 0 &amp;&amp; !hasStructuralAnchors(doc) {<br>        return &amp;SanitizationError{<br>            Cause: ErrCauseNoStructuralAnchor,<br>            ...<br>        }<br>    }<br>    <br>    // ... more checks ...<br>    <br>    // All checks passed - document is repairable<br>    return nil<br>}</pre><p>Caller:</p><pre>err := validateRepairability(doc)<br>if err != nil {<br>    return err<br>}</pre><p>This is preferred when:</p><ul><li>Failure reasons matter more than true/false</li><li>Check is gatekeeping</li><li>Pattern matches ValidateX, CheckX, EnsureX</li></ul><p>This is often more idiomatic than (bool, error) for validation/guard-style checks.</p><h3>Why I Chose Neither</h3><h4>Reason 1: No (false, nil) state exists in my domain</h4><p>In the (bool, error) pattern, there’s this possibility:</p><pre>(false, nil) -&gt; normal business result</pre><p>This doesn’t suit my case. I need the caller to be able to access the structured cause. I want the caller to know the cause of the business rule violation because the purpose is to enrich the logging at the topmost level. This branch of business flow won’t happen. The cause when the document cannot be repaired must be known and enforced, as no operational error will happen downstream that would prevent me from determining <em>why</em> it’s unrepairable.</p><h4>Reason 2: I want to keep domain logic separate from error infrastructure</h4><p>The “return error” pattern was close to being chosen: isRepairable is a gatekeeper (in essence, a validator) and no further flow would be executed if it fails.</p><p>Had I chosen the “return error” pattern, isRepairable (or validateRepairability, in this case) would look like this:</p><pre>func validateRepairability(doc *html.Node) error {<br>    // Check 1: Competing roots<br>    if hasCompetingDocumentRoots(doc) {<br>        return &amp;SanitizationError{<br>            Cause: ErrCauseCompetingRoots,<br>            Message: &quot;competing document roots found&quot;,<br>            Retryable: false,<br>        }<br>    }<br>    <br>    // Check 2: No structural anchors<br>    if len(headings) == 0 &amp;&amp; !hasStructuralAnchors(doc) {<br>        return &amp;SanitizationError{<br>            Cause: ErrCauseNoStructuralAnchor,<br>            Message: &quot;no structural anchors found&quot;,<br>            Retryable: false,<br>        }<br>    }<br>    <br>    // ... more checks ...<br>    <br>    return nil<br>}</pre><p>It becomes polluted by high-level (sanitization, in this case) errors. validateRepairability would be exposed to any other sanitization errors not related to repairing. If you look at my SanitizationError:</p><pre>type SanitizationError struct {<br>    Message   string<br>    Retryable bool<br>    Cause     SanitizationErrorCause<br>}</pre><p>It’s an orchestration-level concern. The Retryable flag, the Message formatting, these are decisions made at the boundary between the sanitization pipeline and the rest of the system, not decisions inherent to the question “is this document repairable?”</p><p>More importantly, if I later need to check repairability in a different context, say, a CLI tool that validates document files, or a completely different service, I’d have to drag SanitizationError along with it. The domain logic would be coupled to infrastructure concerns.</p><h3>The Solution: Domain-Specific Result Type</h3><p>I introduced a repairing-specific struct to wrap the predicate and the reason:</p><pre>// RepairableResult contains the outcome of the repairability check.<br>// If Repairable is false, Reason contains the specific violation type.<br>type RepairableResult struct {<br>    Repairable bool<br>    Reason     UnrepairabilityReason // empty when Repairable is true<br>}</pre><p>And the reason enums:</p><pre>type UnrepairabilityReason string<br><br>const (<br>    // ReasonCompetingRoots: Multiple article/main elements at same level (S3 invariant violation)<br>    ReasonCompetingRoots UnrepairabilityReason = &quot;competing_roots&quot;<br><br>    // ReasonNoStructuralAnchor: No headings and no structural anchors like article/main (H3 invariant violation)<br>    ReasonNoStructuralAnchor UnrepairabilityReason = &quot;no_structural_anchor&quot;<br><br>    // ... more reason enums ...<br>)</pre><p>The function now looks like this:</p><pre>func isRepairable(doc *html.Node) RepairableResult {<br>    // Check 1: Competing roots<br>    if hasCompetingDocumentRoots(docQuery) {<br>        return RepairableResult{Repairable: false, Reason: ReasonCompetingRoots}<br>    }<br>    <br>    // Check 2: No structural anchors<br>    if len(headings) == 0 &amp;&amp; !hasStructuralAnchors(docQuery) {<br>        return RepairableResult{Repairable: false, Reason: ReasonNoStructuralAnchor}<br>    }<br>    <br>    // ... more checks ...<br>    <br>    // All checks passed - document is repairable<br>    return RepairableResult{Repairable: true, Reason: &quot;&quot;}<br>}</pre><p>Then I created a mapper function to translate domain reasons to orchestration-level error causes:</p><pre>// mapReasonToErrorCause maps UnrepairabilityReason to SanitizationErrorCause.<br>// This translation occurs at the sanitize() level to keep isRepairable() independent<br>// of error cause types.<br>func mapReasonToErrorCause(reason UnrepairabilityReason) SanitizationErrorCause {<br>    switch reason {<br>    case ReasonCompetingRoots:<br>        return ErrCauseCompetingRoots<br>    case ReasonNoStructuralAnchor:<br>        return ErrCauseNoStructuralAnchor<br>    <br>    // ... more mappings ...<br>    <br>    default:<br>        return &quot;&quot;<br>    }<br>}</pre><p>The caller becomes:</p><pre>// ...<br><br>if !isParseable(doc) {<br>    return SanitizedDoc{}, &amp;SanitizationError{<br>        Message:   &quot;input document cannot be parsed: nil node or no content&quot;,<br>        Retryable: false,<br>        Cause:     ErrCauseUnparseableDoc,<br>    }<br>}<br><br>result := isRepairable(doc)<br>if !result.Repairable {<br>    cause := mapReasonToErrorCause(result.Reason)<br>    return SanitizedDoc{}, &amp;SanitizationError{<br>        Message:   fmt.Sprintf(&quot;document is not repairable: %s&quot;, result.Reason),<br>        Retryable: false,<br>        Cause:     cause,<br>    }<br>}<br><br>// ...</pre><h3>Why This Design Works</h3><h4>1. Clear Separation of Concerns</h4><p>isRepairable() answers a pure domain question: “Can this document be repaired?” It knows nothing about:</p><ul><li>How errors are structured in the sanitization pipeline</li><li>Whether failures are retryable</li><li>How messages should be formatted</li><li>What observability system I’m using</li></ul><p>This means I can:</p><ul><li>Test isRepairable() without mocking SanitizationError</li><li>Reuse it in other contexts (CLI tools, different services)</li><li>Change error handling without touching domain logic</li></ul><h4>2. Explicit Translation Layer</h4><p>The mapReasonToErrorCause() function is intentional indirection. It enforces that domain reasons and error causes evolve independently. If someone adds a new UnrepairabilityReason, the compiler forces them to update the mapper. This prevents the common bug where you add a new failure case but forget to handle it in error logging.</p><h4>3. Type Safety and Self-Documentation</h4><pre>result := isRepairable(doc)<br>if !result.Repairable {<br>    // result.Reason is available here, can&#39;t be forgotten<br>    cause := mapReasonToErrorCause(result.Reason)<br>    // ...<br>}</pre><p>You can’t forget to check the reason: it’s right there in the struct. Compare this to returning just a boolean, where the caller has to “remember” what might have gone wrong.</p><h3>4. Observability-Friendly</h3><p>Because I translate UnrepairabilityReason to SanitizationErrorCause at the orchestration boundary, the observability layer gets structured, queryable data:</p><pre>h.metadataRecorder.RecordError(<br>    time.Now(),<br>    &quot;sanitizer&quot;,<br>    &quot;Sanitizer.Sanitize&quot;,<br>    mapSanitizationErrorToMetadataCause(*sanitizationError), // &lt;- Uses structured Cause<br>    err.Error(),<br>    attrs, // &lt;- buildErrorAttributes can branch on Cause for rich context<br>)</pre><p>If all failures were just ErrCauseStructurallyIncorrect, I’d lose the ability to:</p><ul><li>Build dashboards showing which validation rules fail most often</li><li>Set different alert thresholds for different failure types</li><li>Debug production issues by filtering logs by specific causes</li></ul><h3>Addressing Potential Concerns</h3><h4>“Isn’t the boolean in RepairableResult redundant?”</h4><p>Technically, yes. You could infer it from Reason == &quot;&quot;. But keeping it explicit has ergonomic value:</p><pre>if !result.Repairable {<br>    // immediately clear what&#39;s happening<br>}</pre><p>versus:</p><pre>if result.Reason != &quot;&quot; {<br>    // requires knowing the convention<br>}</pre><p>The redundancy is a feature, not a bug. It makes the code read more naturally.</p><h4>“Why not just use sentinel errors?”</h4><p>You could define:</p><pre>var (<br>    ErrCompetingRoots = errors.New(&quot;competing_roots&quot;)<br>    ErrNoStructuralAnchor = errors.New(&quot;no_structural_anchor&quot;)<br>)</pre><p>And return these directly. The problem is you lose the boolean answer to “is it repairable?” You’d have to use errors.Is() checks at the call site, which is more awkward:</p><pre>err := validateRepairability(doc)<br>if errors.Is(err, ErrCompetingRoots) {<br>    // handle competing roots<br>} else if errors.Is(err, ErrNoStructuralAnchor) {<br>    // handle no anchor<br>}</pre><p>versus:</p><pre>result := isRepairable(doc)<br>if !result.Repairable {<br>    switch result.Reason {<br>    case ReasonCompetingRoots:<br>        // handle competing roots<br>    case ReasonNoStructuralAnchor:<br>        // handle no anchor<br>    }<br>}</pre><p>The latter is clearer and easier to extend.</p><h4>“This seems like a lot of ceremony for a simple check”</h4><p>It would be, if this were just a simple check. But it’s not, it’s a critical validation point that:</p><ul><li>Gates the entire sanitization pipeline</li><li>Feeds production observability metrics</li><li>Needs to be testable independently</li><li>May be reused in other contexts</li></ul><p>The “ceremony” is buying me maintainability, testability, and clear separation between domain logic and infrastructure concerns. In a small script, this would be overkill. In a production service with observability requirements, it’s appropriate engineering.</p><h3>Lessons Learned</h3><ol><li><strong>Consider the full context</strong>: What seemed like a simple boolean check was actually feeding a sophisticated observability system. The design needed to account for that.</li><li><strong>Domain-orchestration separation matters</strong>: Keeping isRepairable() independent of SanitizationError made the code more testable and reusable.</li><li><strong>Explicit is better than clever</strong>: The mapper function and result struct add lines of code, but they make the system’s behavior explicit and type-safe.</li><li><strong>Error design is about more than error handling</strong>: Good error design supports debugging, observability, and maintenance, not just reporting failures.</li></ol><p>When you’re choosing between (bool, error), error-only, or a custom result type, think about:</p><ul><li>What downstream systems consume this information?</li><li>Will this logic be reused in different contexts?</li><li>What happens when you need to add a new failure case?</li><li>How will this be tested?</li></ul><p>The answers to these questions should guide your design more than following a pattern because it’s “idiomatic.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=260009a5c662" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Agentic Coding for Free: My OpenRouter + Cline Setup]]></title>
            <link>https://medium.com/@rohmanhakim/running-agentic-coding-for-free-my-openrouter-cline-setup-4d86ece7b6ab?source=rss-ee3cbad5a4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d86ece7b6ab</guid>
            <category><![CDATA[cline]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-coding]]></category>
            <category><![CDATA[open-router]]></category>
            <dc:creator><![CDATA[Muhammad Arif Rohman Hakim]]></dc:creator>
            <pubDate>Thu, 05 Feb 2026 04:15:18 GMT</pubDate>
            <atom:updated>2026-02-12T01:04:58.098Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rpC0zXgsAz55vHwDnMQ1nA.png" /></figure><p>I’ve been playing around with agentic coding lately, letting an AI work through coding tasks with minimal hand-holding, and recently stumbled onto a setup that’s genuinely good and costs nothing to run. This post walks through exactly how I got it working, from zero to a working environment, in about ten minutes.</p><h3>But first, what are we even talking about?</h3><p>Before diving into the steps, let me lay out the key terms, because this space moves fast and the jargon stacks up quickly.</p><p><strong>LLM (Large Language Model)</strong> is the engine behind all of this. It’s a type of AI model trained on massive amounts of text, capable of understanding and generating code, answering questions, and reasoning through problems. When people say “AI coding assistant,” there’s an LLM doing the heavy lifting underneath.</p><p><strong>Inference</strong> is what happens when you actually <em>use</em> an LLM: you send it a prompt (like a coding task), and it generates a response. Each inference costs compute resources, which is why providers typically charge per token (a token is roughly a word or a short chunk of text). Every time Cline asks the model to think or write code, that’s an inference happening.</p><p><strong>Context</strong> is everything the model can “see” at any given moment during a conversation: your prompt, the files you’ve attached, the chat history so far, and any other information fed into it. The model has no memory between separate tasks. It only knows what’s inside the current context. This is why feeding it the right files and information matters so much. If it’s not in the context, the model doesn’t know it exists.</p><p><strong>Context window</strong> is the maximum amount of context a model can hold at once, measured in tokens. Think of it as the model’s working memory. If your conversation grows beyond this limit, older parts get dropped. Step 3.5 Flash has a 256,000 token context window, (which is quite generous) but in a long agentic session with many files, it can fill up faster than you’d expect. Cline (which we’ll use later shortly) shows you a progress bar for this so you can keep an eye on it.</p><p><strong>Model</strong> in this context refers to a specific LLM you’re working with. Different models have different strengths, speeds, and costs. Think of them as different tools in your toolkit: you pick the right one for the job.</p><p><strong>Agentic coding</strong> is the practice of giving an AI model a task (sometimes a complex, multi-step one) and letting it work through it autonomously: reading files, writing code, running tests, and iterating, with minimal intervention from you. It’s less “autocomplete on steroids” and more “I have a junior dev who can actually finish tasks.”</p><p><strong>OpenRouter</strong> is a service that acts as a unified gateway to dozens of different LLM providers. Instead of signing up with each AI company separately, you connect to OpenRouter and pick from their catalog of models. Some are paid, some free. It handles routing your requests to the right backend provider. Think of it as an app store, but for AI models.</p><p><strong>Cline</strong> is a VS Code extension that turns your editor into an agentic coding environment. It connects to an LLM (via a provider like OpenRouter) and can autonomously read your codebase, write and edit files, run commands, and iterate on problems. You give it a task, and it works through it step by step.</p><p><strong>StepFun</strong> is a Chinese AI lab (full name: StepFun AI) that develops and open-sources their own family of large language models. Their models have been gaining traction recently due to competitive performance at lower cost.</p><p><strong>Hallucination</strong> is when an LLM generates something that sounds confident and plausible, but is factually wrong or completely made up. In coding, this often shows up as invented function names, incorrect API usage, or logic that looks right at a glance but doesn’t actually work. It’s one of the more frustrating things you’ll run into with weaker models, and one of the quickest ways to tell a good model from a bad one for your use case.</p><h3>Why this setup works</h3><p>The key insight here is that OpenRouter occasionally offers certain models on a <strong>free tier</strong>, meaning zero cost per inference. Right now, one of those free models is <strong>Step 3.5 Flash</strong> from StepFun, and it’s genuinely good.</p><p>Step 3.5 Flash is built on a <strong>Mixture of Experts (MoE)</strong> architecture, a technique where the model has a large total parameter count (196B), but only activates a small subset (11B) for any given task. This makes it fast and efficient. It also has a generous 256,000 token context window, which is more than enough for most coding tasks.</p><p>I’ve been using it for a personal project involving <strong>concurrent Go code with mutex synchronization</strong> and long test scenarios using --race flags. For that kind of medium-complexity reasoning, Step 3.5 Flash handled it quite well, and it was noticeably faster than some paid models I tried on OpenRouter like Kimi or MiniMax.</p><blockquote><strong><em>A note on “free” models:</em></strong><em> Free tiers on OpenRouter can change. StepFun’s model is free </em>right now<em>, but there’s no guarantee it’ll stay that way. My advice: take advantage of it while it lasts, and use it as a low-risk way to learn the agentic coding workflow before committing to a paid model later.</em></blockquote><h3>The Setup</h3><p>Here’s the full process, start to finish. It should take around 10 minutes.</p><h3>Step 1: Create an OpenRouter account and set up billing</h3><p>Go to <a href="https://openrouter.ai/">openrouter.ai</a> and sign up for an account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zpTVl_2chbi8OfD0ihaHQ.png" /></figure><p>Once you’re in, you’ll need to set up billing. OpenRouter uses a <strong>top-up model</strong>: you add credits to your account, and those credits get consumed as you use paid models. Each inference draws down a small amount based on the model’s pricing.</p><p><strong>But here’s the thing: for our setup, you won’t actually be spending credits.</strong> Step 3.5 Flash is on the free tier, so no credits will be deducted. You still need to set up a payment method though. It’s a required step to activate your account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lhzpPeC0eFuNXdqEb4csXg.png" /></figure><p>To set up billing, you’ll need a credit or debit card. OpenRouter will charge a small authorization hold (a few dollars or less) to verify the card (this is completely standard for any online payment platform, and it will be released back to you. It’s not an actual charge).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iZ7gPocg96pKO6dLbg-EsA.png" /></figure><p>Once billing is set up, you need to create an <strong>API key</strong>. An API key is a unique string that lets other tools, like Cline, authenticate with OpenRouter on your behalf, so they can make requests to the models without you logging in each time. Go to <a href="https://openrouter.ai/settings/keys">openrouter.ai/settings/keys</a> and create a new key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*feJsMPJUlwoCVBZofw1oRw.png" /></figure><p>You’ll see four fields to fill in:</p><p><strong>Name</strong> — just a label for yourself. Something like cline-personal works fine.</p><p><strong>Credit Limit</strong> — this caps how much spend this key is allowed before it stops working. For our setup it doesn’t matter since Step 3.5 Flash is free, but if you plan to experiment with paid models later, setting a limit here is a good guardrail so you don’t accidentally burn through credits. Leave it blank for no limit.</p><p><strong>Reset Limit every…</strong> — if you set a credit limit, this controls how often it resets. Options like daily or weekly are available, all resetting at midnight UTC. If you want a hard total cap that never resets, pick “N/A”. If you left the credit limit blank, this doesn’t apply.</p><p><strong>Expiration</strong> — when the key should stop working. Pick “No expiration” for a key that stays active indefinitely.</p><p>For my setup, I left the credit limit blank and set no expiration, simple and low-maintenance. But again, if you’re planning to try paid models down the line, I’d recommend adding a credit limit as a safety net.</p><p><strong>Important: once you create the key, copy it and store it somewhere safe.</strong> OpenRouter will not show it to you again. You’ll need it in a later step when configuring Cline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QiDxTJ0rYxpBiJFm8JcPIg.png" /></figure><h3>Step 2: Download and install Visual Studio Code</h3><p>If you don’t already have it, grab <a href="https://code.visualstudio.com/">VS Code</a> from the official site. It’s free and available for Windows, macOS, and Linux.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HznLdNDhW8-ENrQMhLn7vQ.png" /></figure><h3>Step 3: Install the Cline extension</h3><p>Open VS Code, go to the <strong>Extensions</strong> panel (the puzzle piece icon on the left sidebar, or press Ctrl+Shift+X), and search for <strong>Cline</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RkkDqB6pBygq_2vz-0Y2Ww.png" /></figure><p>Install it, then open the extension on the left panel. You’ll be prompted “How will you use Cline?”, ignore this for now and click “Login to Cline”, you’ll be prompted to SignUp for Cline account, go ahead and do that. This is just to activate the extension and give it a session history feature. No billing or payment is needed on Cline’s side, because we’re going to point it at OpenRouter for the actual model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8IjuJzhr1iw61x-k9xhhfA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pMgoQucKXKPIaTfUlrG0vQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H3a2eBIb5VqV6fKyA05dpg.png" /></figure><h3>Step 4: Configure Cline to use OpenRouter</h3><p>This is where everything gets connected. Once Cline is installed and activated, click the <strong>gear icon</strong> in the top-right corner of the Cline sidebar to open its settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*Alm3RKG8BW5B716pWDfJPA.png" /></figure><p>You’ll see a configuration form with several fields. Fill them in as follows:</p><p><strong>API Provider</strong>: select OpenRouter from the dropdown. This tells Cline to route all model requests through OpenRouter instead of talking to a provider directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*6EBBLztFV6ej2IgrpQvcEw.png" /></figure><p><strong>OpenRouter API Key</strong>: paste the API key you copied in Step 1 here. This is how Cline authenticates with OpenRouter on your behalf.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*EonXE7YXJ8JOXA_cZFgetg.png" /></figure><p><strong>Model</strong>: select or type stepfun/step-3.5-flash:free. This is the specific model Cline will use for all your tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*nGvs_7xQcjm8odrib0TnlA.png" /></figure><p><strong>Enable Thinking (1024 tokens)</strong>: check this box. Step 3.5 Flash is a reasoning model, meaning it has the ability to “think” internally before generating its response, working through the problem step by step before writing code. When this is enabled, Cline allocates a budget of 1024 reasoning tokens for that internal thinking process. It can improve the quality of the model’s output, especially on trickier tasks. The 1024 token budget is Cline’s minimum. It’s a small amount and won’t noticeably affect performance on the free tier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*BIP2Rn7rs5iNOCkAjC52Gg.png" /></figure><p>Once all the fields are filled in, click the <strong>Done</strong> button at the top of the Cline sidebar. That’s it. Cline is now fully wired up to Step 3.5 Flash via OpenRouter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*nxFWQ9dRCZ-B_swRwLcylw.png" /></figure><p>At the <strong>bottom of the Cline sidebar</strong>, you’ll see something like openrouter:stepfun/step-3.5-flash:free. This is a model selector. In case you want to change to another model later, you can click on the model selector there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*4Nq6d-pl39qAxg33IrZv0Q.png" /></figure><h3>Step 5: Try it out</h3><p>Open a project in VS Code, open the Cline panel, and make sure you’re in <strong>Plan mode</strong> (more on that below). Give it a task. Something like:</p><blockquote>“Add input validation to the user registration function and write unit tests for it.”</blockquote><p>The model will read your code, reason through the task, and lay out a plan for you to review before it touches anything. The rest of the workflow (how Plan and Act mode work, how to give it context, and how to keep an eye on your usage) is covered in the next section.</p><h3>A quick look at the model landscape (for context)</h3><p>You might wonder why Step 3.5 Flash and not something else. Here’s a rough picture of what’s out there, some of these I tested through OpenRouter + Cline, others I compared against using a different setup (more on that below):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*jtangASRWmA5eLqSbhuCmA.png" /></figure><p><strong>Kimi</strong> is developed by Moonshot AI, a Chinese AI startup. Their “Thinking” variants are models tuned for extended reasoning. They take longer but can handle harder problems.</p><p><strong>MiniMax</strong> is another Chinese AI company with a range of models across different sizes and capabilities.</p><p><strong>GPT-5-Nano</strong> is OpenAI’s smallest, cheapest model in the GPT-5 family, designed to be fast and low-cost for simpler tasks.</p><p><strong>Gemini 2.5 Flash Lite</strong> is Google’s budget-tier model from the Gemini 2.5 line, similarly positioned for lightweight, cost-effective inference.</p><p><strong>Claude Sonnet 4.5</strong> is Anthropic’s mid-tier model, solid at coding and reasoning tasks.</p><p><strong>Gemini 3</strong> is Google’s latest flagship model, a step up in capability from the 2.5 line.</p><p>I actually tried GPT-5-Nano and Gemini 2.5 Flash Lite before settling on this setup, but on a different tool at the time. I was using <strong>Zed Editor</strong>’s <a href="https://zed.dev/ai">built-in AI </a>coding feature, which lets you connect to various models directly without Cline. For the same level of task I was throwing at Step 3.5 Flash, both GPT-5-Nano and Gemini 2.5 Flash Lite hallucinated noticeably more. They’d generate code that looked reasonable on the surface but used wrong APIs, invented functions that don’t exist, or got the logic subtly wrong in ways that only surfaced when you actually ran the tests. Step 3.5 Flash was significantly more reliable for the same kind of work. And again, it’s free.</p><p>From my experience across both setups, the models roughly shake out into tiers. Step 3.5 Flash sits in the same ballpark as Gemini 2.5 Flash and Claude Sonnet 4.5. All three handled medium-complexity tasks with similar reliability. Above them is a noticeable step up: Gemini 3 and Kimi 2.5 Thinking, which I reached for when tasks got more complex and needed stronger reasoning. So Step 3.5 Flash isn’t just “good enough for free”, it’s actually competitive with paid models at its tier. The question is only whether your tasks eventually outgrow that tier.</p><p>For my use case (medium-level reasoning on real codebases) Step 3.5 Flash hit the sweet spot: fast, capable, and free. If you eventually hit its limits on harder tasks, the paid models are worth exploring, but I’d start here.</p><h3>How I actually use this setup</h3><p>It’s worth setting expectations here. Agentic coding with current LLMs isn’t magic. The model will sometimes misunderstand what you want, go down the wrong path, or need a nudge. But the gap between “AI autocomplete” and “AI that can actually work through a task” is real, and Cline’s workflow is designed around that gap pretty well. Here’s how I use it day to day.</p><h3>Plan mode vs Act mode</h3><p>The single most important thing to understand about Cline is that it has two modes: <strong>Plan</strong> and <strong>Act</strong>. You toggle between them in the <strong>bottom-right corner</strong> of the Cline extension panel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*UIxqQ2KDR2oN0r3jXQ-ybg.png" /></figure><p>In <strong>Plan mode</strong>, the model cannot touch your files. It can read them, but it won’t write or modify anything. This is where you do the thinking together with the model. You describe what you want, and the model breaks it down into a concrete, sequential plan: the steps it would take to actually execute the task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oJ4RKRR4aFvz-9rps0ETJQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t4P3E-vuP0c_lizRkhSCZA.png" /></figure><p>This is where the real value is, honestly. Before the model writes a single line of code, you get to look at its plan and say “no, that’s wrong, do it this way instead.” You can go back and forth with it, refine the plan, poke holes in it. It’s like reviewing a design doc before someone starts coding. Only when you’re happy with the plan do you move on.</p><h3>Giving the model context</h3><p>The model can only work with what it knows about your project, so feeding it the right context matters. This is one of the things that separates decent results from great ones. If you just type “fix the bug” without pointing the model at the relevant files, it’s guessing. Point it at the right files, and suddenly it can actually reason about your code. The difference in output quality is noticeable.</p><p>Cline gives you two ways to do this.</p><p>The first is the @ mention. Type @ in the prompt message box and you can point the model at specific files in your project. If you’re working on a bug in auth/handler.go, just type @auth/handler.go and it’ll pull that file into the conversation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*L-VDUQlpTqE_QI4GaipBWg.png" /></figure><p>The second is the + button at the bottom of the prompt message box. This lets you add external context (things outside your project) that are relevant, like documentation or reference material.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*UUnf_BjZJmpC1jGRTCQ2qA.png" /></figure><h3>From plan to execution</h3><p>Once you’re satisfied with the plan, toggle over to <strong>Act mode</strong>. If a plan has already been generated in Plan mode, the model starts executing it immediately, no additional prompt needed. It just goes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qsHe7boFQnZDXEAqK5HYng.png" /></figure><p>As it works, Cline opens a diff view in your editor that looks like VS Code’s built-in git diff, the familiar red and green line-by-line comparison. The title bar will say <strong>“Cline’s Changes”</strong> so you know what you’re looking at. You can watch the model’s progress in real time as it edits files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k2YXUvx8C09sM-7w4vFj6g.gif" /></figure><h3>Approvals and permissions</h3><p>Here’s an important detail: <strong>the model can’t save anything without your say-so.</strong> After it makes changes to a file, Cline will prompt you to review and click <strong>Save</strong> to confirm. This is by design, you’re the last checkpoint before anything actually gets written to disk.</p><p>The same applies to running commands. If the model wants to execute something on the command line (like running tests), it’ll ask for your approval first before doing so.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*WuyqWonlhp1KD0YPPbVjOw.png" /></figure><p>That said, if you find yourself clicking Save on every single small change and it’s slowing you down, you can adjust this. At the top of the prompt message box, there’s an <strong>Auto-approve</strong> setting. You can configure which actions the model is allowed to do without asking. Saving files, running specific commands, and so on. I’d recommend keeping it conservative when you’re starting out, and loosening it once you get a feel for how the model behaves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*2ZCJ7X5TaIuh5bethGZv5w.png" /></figure><h3>Watching your token usage and cost</h3><p>At the very top of the Cline extension, you’ll see a <strong>progress bar</strong> showing your context usage for the current task. This tracks the total tokens consumed, both input (what you and the model have said) and output (what the model has generated), against the maximum context window allowed by the model. For Step 3.5 Flash, that’s 256K tokens.</p><p>This bar <strong>resets every time you start a new task</strong>, so each conversation in Cline is its own isolated session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*es45Wd368tnNozLVGDT_uw.png" /></figure><p>Right above that bar, there’s a <strong>cost counter</strong> showing how many dollars the current task has consumed on OpenRouter. For Step 3.5 Flash it’ll stay at $0.00, but this becomes very useful once you start experimenting with paid models. It’s the fastest way to keep an eye on your spend without having to log into OpenRouter every time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*D_bzS4hS1JxRf5zNGKrxGA.png" /></figure><h3>.clinerules — giving the model standing instructions</h3><p>One last thing that’s made a big difference in my workflow: the .clinerules file. Place a file named exactly .clinerules in the <strong>root directory</strong> of your project, and whatever you write in it becomes a standing instruction that the model reads at the start of every task. It has to be in the root, as subdirectories won’t work.</p><p>Think of it like a README for the AI. You can put anything there that you’d otherwise have to repeat every time: coding style preferences, project conventions, things to avoid, testing requirements. For example:</p><ul><li>Always use table-driven tests for Go code</li><li>Never modify go.mod unless explicitly asked</li><li>When writing mutex code, always pair Lock() with defer Unlock()</li><li>Run go vet before finishing any task</li></ul><p>This is similar in spirit to AGENTS.md (used by some other AI coding tools) or Claude’s project-level instructions. It’s just Cline’s version of the same idea.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7w9SL8cpHEotliDEsL_hqw.png" /></figure><h3>When the model isn’t enough</h3><p>One thing I appreciated about Cline: it’s upfront when it thinks you might be hitting the limits of your chosen model. When I threw a more complex task at it recently, Cline popped up with this warning:</p><blockquote>Cline uses complex prompts and iterative task execution that may be challenging for less capable models. For best results, it’s recommended to use Claude 4 Sonnet for its advanced agentic coding capabilities.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*evFDzreQlZ5jNcGzW6InRA.png" /></figure><p>It’s a helpful nudge. It doesn’t stop you from continuing. You can ignore it and keep going, but it’s a signal that the task might be too heavy for the current model and you might want to swap to something more capable. If you start seeing this, it’s worth considering whether to switch to a stronger (paid) model for that particular task. For the medium-complexity stuff Step 3.5 Flash handles well, you won’t see it.</p><h3>Putting it all together</h3><p>The workflow I’ve settled into looks something like this: open a project, drop in some context with @, describe the task in Plan mode, review and tweak the plan until it looks right, toggle to Act, watch it work, approve the changes, and move on. For my personal project (go concurrency, mutex synchronization, long test scenarios with --race flags) Step 3.5 Flash would often nail the structure on the first or second pass. That’s the kind of productivity gain that makes this whole setup worth the ten minutes it took to get running.</p><h3>Recap</h3><ol><li>Sign up on OpenRouter, set up billing, and create an API key (no actual spend needed for our setup)</li><li>Install VS Code if you haven’t already</li><li>Install Cline from the VS Code extensions, create an account</li><li>Configure Cline: set OpenRouter as the provider, paste your API key, select stepfun/step-3.5-flash:free, enable thinking</li><li>Start giving it tasks and see how it goes</li></ol><p>The whole point of this post is to lower the barrier. You don’t need a paid subscription, you don’t need to understand the internals of how LLMs work, and the setup itself is straightforward. Just a few accounts and a handful of fields to fill in. Just follow these steps and you’re coding with an AI agent in minutes.</p><p>Give it a shot while Step 3.5 Flash is free. And if you want to share how it goes, or what models you end up preferring. I’m always curious to hear.</p><p>Thank’s for reading, and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d86ece7b6ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Opinion on Writing Test and Engineering Blog Posts]]></title>
            <link>https://medium.com/@rohmanhakim/an-opinion-on-writing-test-and-engineering-blog-posts-a7a8b8b8221c?source=rss-ee3cbad5a4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7a8b8b8221c</guid>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[anecdotes]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Muhammad Arif Rohman Hakim]]></dc:creator>
            <pubDate>Sun, 21 Apr 2019 05:06:25 GMT</pubDate>
            <atom:updated>2019-04-21T11:41:27.384Z</atom:updated>
            <content:encoded><![CDATA[<p>The other day, i read a blog post written by a certain software developer about his opinion on how a good developer should write a test. His post points out that writing test code is different than writing implementation code. Implementation code is about abstraction while test code is about readability. We can, and suggested to break some common discipline (eg. DRY) when writing test code in order to maximize the readability.</p><p>As i usually did when i just read some internet post or article, especially if it’s related to my job, i’d like to discuss it with a friend. So i talked with a coworker of mine. He is self-declared opinionated guy, and an experienced software developer in his mid 30s. He also often becomes someone we consult about technicality in our team. I showed him the post and asked about his opinion.</p><p>After reading it for awhile, his opinion is kinda opposite to the author. He said the examples provided by the author is too small-scaled and it will be bad if we follow the author’s opinion blatantly. The author’s example showed that adding some verbosity is okay as long as it makes programmers understand what the test do from just looking at one test function.</p><p>It is okay if the our test code’s scale is small, like for example, our own apps or something. For a large-scale app, like the company he and i worked at, usually have a lot of preparations before a functionality in which we want to test will be called. Putting all of this preparation code in all of the test functions is very bad.</p><p>The other thing he pointed out was an enterprise-level team like us, usually have a convention that is more important to write some part of the code to be like our personal preference (he mean if we want to write like that author advise).</p><p>He also said that that’s why he hates technical blog post or engineering blogs in general. It can be misleading for junior programmers. They usually will take the authors opinions as is because of his regards towards the author who he seen as more experienced than them, while my coworker said it still counts as one person’s opinion from the internet. If the junior programmer not careful enough he/she will be dogmatized by the author’ opinion. It applies not only for engineering blog but also for all software engineering books out there like book about software architectures or refactoring.</p><p>I personally think that a blog post like what we discussed is not bad. I believe that the author’s intention is not to dictate other programmers but just to express his preferences or opinions, which usually comes from his experience.</p><p>It also depends on us the readers, the programmers, who need to be open-minded and train our habits to think after reading some engineering blogs. This kind of blog’s function, in my opinion, is to share and discuss ideas with other people. That’s why there is comment section in the end of a blogpost isn’t it?</p><p>And of course this post is just my opinion :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7a8b8b8221c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Set Up Code-Completion for Vim in macOS]]></title>
            <link>https://medium.com/@rohmanhakim/how-to-set-up-code-completion-for-vim-in-macos-9766dd459385?source=rss-ee3cbad5a4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/9766dd459385</guid>
            <category><![CDATA[code-completion]]></category>
            <category><![CDATA[intellisense]]></category>
            <category><![CDATA[vim]]></category>
            <dc:creator><![CDATA[Muhammad Arif Rohman Hakim]]></dc:creator>
            <pubDate>Sun, 31 Mar 2019 16:16:12 GMT</pubDate>
            <atom:updated>2022-02-24T02:35:49.086Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*tp-4uCpQ76JTviqNLk55rw.gif" /></figure><p>Until now, vim is arguably one of the most popular text editor loved for its simplicity and, yes, the awesome shortcuts (command-line mode).</p><p>Most developers already satisfied with vim for what it is, but other developers, like me, sometimes miss the code-completion or IntelliSense featured in modern GUI-based text editor.</p><p><a href="https://github.com/neoclide/coc.nvim">COC or Conquer of Completion</a> is an intellisense engine by neoclide for vim8 &amp; neovim. It allows vim to have code-completion feature like modern editors.</p><p>This post will guide us how to do it in macOS.</p><h4>Install Vim 8.1</h4><p>COC needs vim ≥ 8.1 as requirement, if your macOS’s vim version is outdated, it is recommended not to overwrite it. Instead, install another vim with latest version and make an alias. Here’s how to do it:</p><ol><li>Install <a href="https://macvim-dev.github.io/macvim/">MacVim</a> via Homebrew.</li></ol><pre>$ brew install macvim</pre><p>2. Verify the installation. Make sure it installs the latest version. Normally it will have conflicts with the macOS vim since macvim will installs the same vi binaries, but that’s okay.</p><pre>$ brew info macvim</pre><pre>==&gt; macvim: stable 8.1-155, HEAD<br>GUI for vim, made for macOS<br><a href="https://github.com/macvim-dev/macvim">https://github.com/macvim-dev/macvim</a><br>Conflicts with:<br>  vim (because vim and macvim both install vi* binaries)<br>/usr/local/Cellar/macvim/8.1-155 (2,205 files, 35.3MB) *<br>  Built from source on 2019-03-31 at 21:29:24<br>From: <a href="https://github.com/Homebrew/homebrew-core/blob/master/Formula/macvim.rb">https://github.com/Homebrew/homebrew-core/blob/master/Formula/macvim.rb</a><br>==&gt; Dependencies<br>Required: cscope ✔, lua ✔, python ✔<br>==&gt; Requirements<br>Build: xcode ✔<br>==&gt; Options<br>--HEAD<br> Install HEAD version<br>==&gt; Analytics<br>install: 8,594 (30 days), 33,678 (90 days), 210,243 (365 days)<br>install_on_request: 7,866 (30 days), 30,453 (90 days), 181,256 (365 days)<br>build_error: 0 (30 days)</pre><p>3. Add alias to the Homebrew’s newly installed macvim. Add these lines in ./zshrc or ./bashrc.</p><pre>alias vim=&#39;/usr/local/Cellar/macvim/8.1-155/bin/vim&#39;</pre><p>4. Dont forget to call source command to .zshrc or .bashrc.</p><pre>source ~/.zshrc</pre><p>5. Verify it by calling vim command. It should have the latest version now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5uLFkkue9HZmmSSRoj0mrA.png" /></figure><h4>Install vim-plug</h4><p><a href="https://github.com/junegunn/vim-plug">vim-plug</a> is a package manager for vim.</p><ol><li>Download vim-plug and move plug.vim to ~/.vim/autoload directory.</li></ol><pre>curl -fLo ~/.vim/autoload/plug.vim --create-dirs \<br>    <a href="https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim">https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim</a></pre><h4>Install COC</h4><p>You can follow the guide in the <a href="https://github.com/neoclide/coc.nvim/wiki/Install-coc.nvim">official github page</a> for the latest instruction, but, to save your time, i’ll give it below. Although, it will not be guaranteed for future releases.</p><ol><li>Make sure you have nodeJS ≥ 8.0, or else download it via the command below.</li></ol><pre>curl -sL install-node.now.sh | sh</pre><p>2. Install yarn.</p><pre>curl --compressed -o- -L https://yarnpkg.com/install.sh | bash</pre><p>3. Create directory for COC’s installation.</p><pre>mkdir ~/.vim/pack/coc/start</pre><p>4. Clone COC’s repo.</p><pre>cd ~/.vim/pack/coc/start<br>git clone https://github.com/neoclide/coc.nvim.git --depth=1</pre><p>5. Install COC.</p><pre>cd ~/.vim/pack/coc/start/coc.nvim<br>yarn install</pre><p>6. Add Plug for COC. Open ~/.vimrc in editor and add the lines below.</p><pre>call plug#begin()</pre><pre>Plug &#39;neoclide/coc.nvim&#39;, {&#39;do&#39;: { -&gt; coc#util#install()}}</pre><pre>call plug#end()</pre><p>7. Open vim and execute :PlugInstall in the command-line mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*swZr_9KMoxFupTC8mz6teA.png" /></figure><p>8. COC will be installed via vim-plug. when the installation succeed, you will see the screen below inside vim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*gLK0XFifOzZKFCm89ZrHZw.png" /></figure><h4>Install COC Extension</h4><p>The last steps is the installation of the language server you want to use with the code-completion.</p><p>You can see the list of available extensions <a href="https://www.npmjs.com/search?q=keywords%3Acoc.nvim">here</a>. Make sure to follow the requirements of the extensions you want to install as they’re different with each other.</p><p>For this example, I will use Java language server.</p><ol><li>Execute :CocInstall coc-java in the vim’s command-line mode.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*npXesv5yXyyGU6bat8ytdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mUokYpSB9-0YUBFI3I61Pg.png" /></figure><p>2. Open Java source code with vim and see if the code-completion works. Because coc-java requires <a href="https://github.com/eclipse/eclipse.jdt.ls">jdt</a>, and it’s not available yet on my machine, COC will install it the first time I open a Java source code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yDBzuyGuXrDUsEKmoTYpaw.png" /></figure><p>3. Re-open the Java source code and try to type to see if the code completion works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*tp-4uCpQ76JTviqNLk55rw.gif" /></figure><p>It works like a charm :)</p><p>To manage the extensions you can read the guide in the <a href="https://github.com/neoclide/coc.nvim/wiki/Using-coc-extensions">official page</a>.</p><p>And that’s how to enable vim’s code-completion in macOS.</p><p><em>Have a nice day and happy coding!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9766dd459385" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Membangun Vidio Android CI/CD dengan Jenkins, Google Compute Engine dan Genymotion Cloud]]></title>
            <link>https://medium.com/vidio/membangun-vidio-android-ci-cd-dengan-jenkins-google-compute-engine-dan-genymotion-cloud-1f279c8d9b7e?source=rss-ee3cbad5a4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f279c8d9b7e</guid>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[continuous-delivery]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[genymotion-cloud]]></category>
            <dc:creator><![CDATA[Muhammad Arif Rohman Hakim]]></dc:creator>
            <pubDate>Wed, 13 Mar 2019 15:58:48 GMT</pubDate>
            <atom:updated>2019-03-18T17:20:20.252Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vkEe4n21VaOLyjpMxmltYA.png" /></figure><h3>Migrasi Vidio Android CI/CD dengan Jenkins, Google Compute Engine dan Genymotion Cloud</h3><p>Tim Vidio Android melakukan migrasi infrastruktur CI/CD untuk memfasilitasi kami dalam melakukan TDD yang lebih cepat dan optimal. Tulisan ini akan membahas seperti apa dan bagaimana kami melakukannya.</p><h3>Test-Driven Development dan CI/CD di Vidio Android</h3><p>Dalam melakukan pekerjaan setiap harinya, tim Vidio Android menggunakan metode <a href="https://technologyconversations.com/2014/09/30/test-driven-development-tdd/"><strong><em>Test-Driven Development</em></strong> <strong><em>(TDD)</em></strong></a>. Dengan kata lain, tes, baik itu <em>unit test</em> atau <em>UI test</em>, adalah bagian vital dari pekerjaan kami.</p><p>Seperti halnya di tim <em>engineering</em> manapun, kami membutuhkan sistem <a href="https://devops.com/continuous-integration-vs-continuous-delivery-theres-important-difference/"><strong><em>continuous integration (CI)</em></strong> dan <strong><em>continuous delivery (CD)</em></strong></a> untuk memfasilitasi pekerjaan kami.</p><p><em>Continuous integration</em> dalam artian kode yang di-<em>commit</em> oleh para <em>engineer</em> harus secepat mungkin diintegrasikan di<em> master branch</em>, dan <em>continuous delivery</em> dalam artian kode yang telah di-<em>commit</em> secepat mungkin harus menghasilkan sebuah <em>deliverable</em>, atau dalam konteks kami, berbentuk aplikasi Vidio Android.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lg_Z1nEyrd_VVom6-jNV_w.png" /><figcaption>Gambar 1. Apa yang kami butuhkan dari CI/CD?</figcaption></figure><p>Vidio Android sendiri adalah sebuah <em>project</em> aplikasi Android yang modular, artinya dalam satu <em>project</em> Android tersebut, kami memecahnya menjadi beberapa <em>module/library</em> yang bertugas mengurusi fitur yang spesifik.</p><p>Gambar 1 di atas mengilustrasikan apa saja yang kami butuh lakukan di dalam sistem CI/CD. Kami me-<em>maintain</em> 5 modul: Vidio Android, Vidio Android TV, KMK Player (<em>library video player in-house</em>), Plenty (<em>library analytics in-house</em>), dan Stump (<em>library logging in-house</em>).</p><p>Semua modul tersebut (kecuali Android TV) di-<em>maintain</em> di <em>repository</em> yang terpisah, dan semua <em>repository</em> tersebut membutuhkan CI/CD yang akan menjalankan test dan membuat <em>artifact</em>. Selain itu,<em> Test Engineer </em>(TE) juga butuh untuk menjalankan serangkaian <em>robot test</em> dari <em>artifact</em> Vidio Android yang telah lolos unit dan UI test.</p><h3>Release Cycle Vidio Android</h3><p>Vidio adalah sebuah tim yang <a href="https://agilemanifesto.org/"><em>agile</em></a>. Dalam <em>release cycle</em>, kami membutuhkan sistem yang dapat menghasilkan artifact yang cepat untuk di tes, agar tim engineer segera mendapatkan feedback dan kualitas kode kami tetap terjaga.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f3HBIUpijgmoL986W64Cng.png" /><figcaption>Gambar 2. Release Cycle Vidio Android</figcaption></figure><p>Ketika <em>engineer</em> melakukan <em>commit</em> kode ke <em>master branch</em>:</p><ol><li>Sistem CI/CD kami harus menjalankan semua<em> unit test</em> dan UI <em>test</em></li><li>Untuk kemudian jika telah lolos, sistem akan melanjutkan dengan membuat <em>artifact debug</em> untuk <em>flavor staging</em> dan <em>production</em>.</li><li>Sistem kemudian akan membuat sebuah <em>git</em> <em>tag</em> unik dan melakukan <em>push</em> terhadap <em>tag</em> tersebut ke <em>remote repository</em>.</li><li>TE kemudian akan mengambil <em>artifact</em> terbaru, melihat <em>git tag</em> dan <em>changelog</em>, kemudian melakukan <em>sanity test</em> sesuai dengan kebutuhan rilis.</li><li>Jika telah lolos, kami akan menginstruksikan sistem untuk membuat <em>artifact release</em>.</li><li>Ketika akan rilis, kami kemudian akan melakukan <em>publish</em> di Play Store menggunakan <em>artifact release</em> yang tersedia dan disesuaikan dengan kebutuhan.</li></ol><h3>Infrastruktur CI/CD Vidio Android yang Lama</h3><p>Sebelum migrasi, tim Vidio Android menggunakan sistem CI/CD bersama dengan tim Vidio iOS. Jadi bisa dikatakan sebenarnya kami tidak memiliki sistem CI/CD sendiri sebelumnya.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mKQpncaZES7mpU5P" /><figcaption>Gambar 3. Diagram Infrastruktur Sistem CI/CD Vidio Android yang lama</figcaption></figure><p>Infrastruktur sistem CI/CD tim Vidio Mobile App untuk tim Android sebelum migrasi adalah diilustrasikan seperti di gambar 3.</p><p>Kami menggunakan <a href="https://jenkins.io/"><em>Jenkins</em></a>, <em>server automation open-source</em> paling populer, yang di-<em>host</em> di <em>platform</em> <a href="https://aws.amazon.com/"><em>Amazon Web Services</em> (AWS)</a> dalam bentuk sebuah <a href="https://en.wikipedia.org/wiki/Virtual_machine"><em>virtual machine</em> (VM)</a> bertipe<a href="https://aws.amazon.com/ec2/"><em> Amazon Elastic Compute Cloud 2 </em>(EC2)</a>. VM di mana Jenkins itu sendiri di-<em>host</em>, untuk selanjutnya disebut <strong><em>master node</em></strong>.</p><p>Ketika sebuah Jenkins <em>job</em> dijalankan, <em>master node</em> akan mendelegasikan <em>job</em> tersebut ke sebuah VM EC2 lain yang akan melakukan<em> clone repository</em>, menjalankan tes (<em>small, medium, large</em>), membuat <em>artifact</em>, dan sebagainya. VM yang bertugas menjalankan <em>job</em> tersebut untuk selanjutnya disebut <strong><em>slave node</em></strong>.</p><p>Untuk dicatat bahwa <em>slave node</em> yang dipakai untuk menjalankan semua <em>job</em> itu adalah VM yang sama. Artinya, jika ada sebuah <em>job</em> yang sedang menjalankan <em>small test</em>, kami tidak dapat menjalankan <em>job</em> lain, misal <em>medium test</em>, di waktu yang bersamaan. Kami harus menunggu sampai <em>job small test </em>tersebut selesai. Begitu juga untuk <em>job-job</em> yang lain.</p><p><em>Medium test</em> dan <em>large test</em> adalah <em>android UI test</em> (<em>instrumentation test</em>), yang artinya kami membutuhkan emulator untuk menjalankannya. Kami menggunakan <a href="https://firebase.google.com/docs/test-lab/"><strong><em>Firebase Test Lab</em></strong></a> untuk menyediakan android <em>device</em> bagi tes-tes ini. Karena kami menggunakan akun Firebase bertipe <em>Spark</em>, kami dibatasi hanya boleh menggunakan maksimal 10 android <em>device</em> setiap harinya.</p><p>Selain itu, ada <em>slave node</em> lain yang bertugas menjalankan <em>robot test</em> milik TE. <em>Slave node</em> ini adalah sebuah <em>local machine</em> (komputer/PC) yang ada di kantor kami. Karena <em>robot test</em> juga membutuhkan android<em> device</em>, kami juga menyediakan android <em>device</em> sendiri di <em>slave node</em> tersebut.</p><h4>Bagaimana Kami Menjalankan Tes Vidio Android di CI/CD yang Lama</h4><p>Di sistem kami yang lama, kami memecah tes-tes di Vidio Android menjadi 3 jenis, yaitu <em>small, medium</em>, dan <em>large</em>. <em>Small test </em>adalah <em>unit test</em>, <em>medium test </em>adalah UI <em>test</em>, dan <em>large test</em> adalah <em>acceptance test</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/0*eYMO37XxRbnfqFDv" /><figcaption>Gambar 4. Alur tes Vidio Android di CI/CD lama</figcaption></figure><p>Karena memakai<em> slave node</em> yang sama, ketiga <em>job</em> tes tersebut akan dijalankan bergiliran setelah <em>job</em> sebelumnya sukses. <em>Medium test</em> dan <em>large test </em>akan melakukan reservasi <em>device</em> di Firebase Test Lab ketika dijalankan.</p><h4>Test Reporting di CI/CD yang Lama</h4><p>Setelah menjalankan tes, <em>report</em> untuk tes yang gagal, sukses, atau yang diabaikan (<em>ignored</em>) semuanya disediakan oleh Firebase Test Lab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*azUlFt2v5Z4Ihjvr" /><figcaption>Gambar 5. Firebase Test Lab Test Report</figcaption></figure><p>Laporan yang disediakan oleh Firebase Test Lab ini cukup bagus dan informatif. Secara<em> high-level </em>kita bisa melihat di <em>emulator</em> mana tes kami dijalankan dan statusnya. Secara <em>low-level</em>, kami bisa melihat<em> test case</em> mana yang gagal dan penyebabnya. Kami juga bisa melihat <em>logCat</em> <em>device</em> dari tiap testcase. Yang menarik, Firebase Test Lab menyediakan fitur untuk melihat video tes kami dan analisis performanya.</p><h3>Migrasi ke Sistem CI/CD yang Baru</h3><p>Di sistem CI/CD yang baru ini, kami melakukan perubahan besar, di mana kami tidak lagi menggunakan platform AWS dan Firebase Test Lab. Sebagai gantinya, kami menggunakan <a href="https://cloud.google.com/"><strong><em>Google Cloud Platform</em></strong></a> sebagai penyedia VM dan <a href="https://www.genymotion.com/cloud/"><strong><em>Genymotion Cloud</em></strong></a> sebagai penyedia Android <em>device</em>. Namun kami masih tetap menggunakan Jenkins sebagai<em> automation server</em>-nya.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yLuyRYq_T7b0yTvT1ze9Pg.png" /><figcaption>Gambar 6. Diagram Infrastruktur CI/CD Vidio Android yang Baru</figcaption></figure><p>Dari desain infrastruktur sebenarnya hampir sama dari CI/CD kami yang lama, hanya saja, kali ini ada 3 jenis <em>slave node</em>. Yang pertama adalah <em>slave node </em>yang khusus untuk menjalankan tes, kami sebut sebagai <em>test runner</em> (warna merah muda pada gambar 6). Kemudian ada <em>artifact builder</em>, <em>slave node</em> yang digunakan khusus untuk membuat <em>artifact</em> (warna hijau), dan terakhir <em>slave node</em> untuk menjalankan<em> robot test</em> TE (warna kuning).</p><p>Karena kali ada <em>slave node</em> khusus untuk jenis <em>job</em> berbeda, maka kami dapat melakukan, misalnya, menjalankan <em>job</em> untuk tes dan <em>job</em> untuk membuat <em>artifact</em> tanpa perlu saling menunggu satu sama lain. Hal ini tentunya meningkatkan produktivitas kami. Antrian hanya terjadi pada <em>job</em>-<em>job</em> yang berjalan di<em> slave node</em> yang tipenya sama, dan itu pun jika jumlah <em>instance</em> <em>slave node</em> tipe tersebut sudah mencapai batas maksimal yang telah kami tentukan.</p><p>Untuk <em>test runner</em> dan <em>robot test node</em> sama-sama menggunakan Genymotion Cloud untuk menyediakan Android <em>device</em>. Dengan Genymotion Cloud, kami dapat menjalankan sampai 100 Android <em>device</em> secara bersamaan.</p><p>Semua <em>node</em>, baik <em>master node</em> maupun <em>slave node</em> adalah sebuah VM bertipe <a href="https://cloud.google.com/compute/"><strong><em>Google Compute Engine (GCE)</em></strong></a>. Setiap ada <em>job</em> baru yang akan dijalankan, <em>master node</em> akan membuat sebuah <em>instance</em> GCE baru untuk dijadikan <em>slave node</em> sesuai tipe <em>job</em>. Ketika <em>job</em> tersebut sudah selesai, dan tidak ada <em>job</em> lain dengan tipe sama yang mengantri, maka VM tersebut akan dimatikan. Jika ada <em>job</em> baru yang akan dijalankan, <em>master</em> akan membuat lagi yang baru, begitu seterusnya.</p><h4>Bagaimana Instance Slave Node Baru Dibuat</h4><p><em>Master node </em>memiliki sebuah <em>job</em> yang khusus yang bernama “<em>create image</em>”. Ketika <em>job</em> ini dijalankan, ia akan melakukan <em>clone</em> ke sebuah <em>repository</em> kami bernama “skilla”, yang di dalamnya terdapat script <em>playbook</em> <a href="https://www.ansible.com/"><strong><em>Ansible</em></strong></a> berisi semua <em>dependency</em> yang dibutuhkan sebuah <em>job</em> ketika dijalankan, seperti Android SDK, Gradle, Genymotion <em>tools</em>, dll.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dsiOrUjv3bTxz1zxMF8Utw.png" /><figcaption>Gambar 7. Alur Master Node Membuat Instance Slave Node</figcaption></figure><p>Melalui <em>job create image</em>, <em>script</em> ini kemudian dijalankan, melakukan <em>provisioning</em> dan menghasilkan <em>output</em> berupa <em>image</em>. Image ini adalah sebuah cetak biru VM yang akan dipakai oleh sebuah <em>job</em>.</p><p>Jadi ketika misalnya sebuah <em>job</em> bertipe <em>test runner </em>akan dijalankan, Jenkins akan mencari <em>image</em> untuk <em>job</em> <em>test runner</em> (yang membutuhkan Android SDK dan Genymotion <em>tools</em>) di GCP (hasil dari<em> job create image</em>), kemudian akan diluncurkan menjadi VM dan dipakai <em>job test runner </em>tadi sebagai <em>slave node</em>.</p><p>Ketika selesai, VM ini akan menunggu selama waktu tertentu yang telah kami tentukan (disebut <em>retention time</em>) apakah ada <em>job test runner </em>lain yang akan dijalankan. Jika ada, maka VM ini akan dipakai lagi, dan jika tidak, ia akan dimatikan.</p><h4>Bagaimana Vidio Android Menjalankan Tes di CI/CD Yang Baru</h4><p>Kali ini kami tidak lagi memecah tes menjadi <em>small</em>, <em>medium</em> dan <em>large</em>, namun kami membaginya menjadi per modul.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/0*SHngcrUBm-COjBwX" /><figcaption>Gambar 8. Alur Job Test Runner Menjalankan Tes</figcaption></figure><p>Kami membuat sebuah <a href="https://jenkins.io/doc/book/pipeline/"><strong><em>pipeline</em></strong></a>, membaginya menjadi empat tahap: <em>unit test </em>(untuk semua modul), <em>platform</em> UI <em>test</em>, <em>app</em> UI <em>test</em>, dan TV <em>unit test</em>.</p><p>Ketika <em>job</em> ini jalan, ia akan mereservasi 4 buah <em>emulator</em> dari Genymotion Cloud, 3 berupa <em>smartphone</em>, dan 1 berupa <em>tablet</em>.</p><p><em>Unit test</em> akan dijalankan pertama kali, jika ada tes yang gagal maka <em>job</em> akan dibatalkan. Dilanjutkan dengan menjalankan UI <em>test</em> untuk modul <em>platform</em>, yang merupakan salah satu modul vital Vidio Android dan merupakan <em>dependency</em> dari modul <em>app</em> dan <em>tv</em>. Modul <em>platform</em> akan memakai keempat <em>emulator</em> yang telah direservasi tadi untuk menjalankan UI <em>test</em>.</p><p>Jika lolos, <em>job</em> akan menjalankan UI <em>test</em> untuk modul <em>app</em> dan <em>tv</em> secara <em>paralel</em>, karena kedua modul tersebut tidak bergantung satu sama lain. Module <em>app</em> akan memakai ketiga <em>smartphone</em> emulator, sedangkan <em>tv</em> akan memakai 1 <em>tablet</em> <em>emulator</em>. Konfigurasi ini dapat berubah di masa yang akan datang.</p><h4>Spoon</h4><p>Dalam menjalankan UI <em>test</em>, kami memutuskan untuk menggunakan <a href="http://square.github.io/spoon/"><strong><em>Spoon</em></strong></a>, sebuah aplikasi UI <em>test-runner</em> <em>open source </em>buatan <a href="https://squareup.com/">Square</a>, sebagai <em>test-runner</em> UI <em>test</em> kami karena beberapa fitur yang telah disediakan olehnya, antara lain:</p><ul><li>UI Test Sharding</li><li>UI Test Isolation</li><li>High Level UI Test Reporting</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/0*bHA_3iN_ksmj7Osn" /><figcaption>Gambar 9. Spoon’s Homepage</figcaption></figure><p>Kenapa kami membutuhkan fitur-fitur ini tentunya karena banyak faktor, dan salah satunya adalah efisiensi waktu dan <em>resource</em>.</p><p>Beberapa paragraf di bawah akan membandingkan antara <em>unsharded test </em>vs <em>test sharding</em> dan <em>unisolated test</em> vs <em>isolated test</em>.</p><h4>Unsharded Test</h4><p>Ketika kita menjalankan serangkaian UI <em>test</em>, misal dalam sebuah modul, tes tersebut akan dijalankan satu-persatu terhadap <em>device</em> yang tersedia, seperti diilustrasikan pada gambar berikut:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cSEmOsz3GLUxg9Dk" /><figcaption>Gambar 10. Unsharded Test</figcaption></figure><p>Pada gambar 10, <em>test A </em>akan dijalankan pertama kali,<em> test J </em>akan dijalankan setelah <em>test I </em>selesai,<em> test K </em>akan dijalankan setelah <em>test J</em>, dan seterusnya. Hal ini tentunya akan membutuhkan banyak waktu.</p><h4>Test Sharding</h4><p><em>Test sharding</em> akan membagi serangkaian tes tersebut tadi menjadi beberapa grup sebanyak <em>device</em> yang tersedia, kemudian menjalankannya secara <em>paralel</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/0*5WcPFg_cEI9h9IZk" /><figcaption>Gambar 11. Test Sharding</figcaption></figure><p>Bagaimana tes-tes tersebut dibagi, Spoon memiliki algoritma sendiri, dan selama kami pantau, sepertinya hasilnya cukup imbang untuk tiap grupnya.</p><h4>Unisolated Test</h4><p>Salah satu fitur Spoon adalah<em> test isolation</em>. Untuk memahaminya kita perlu memahami <em>unisolated test</em> terlebih dulu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jMFM0N_Ie28AxP4v" /><figcaption>Gambar 12. Apa Yang Terjadi Ketika Android UI Test Dijalankan</figcaption></figure><p>Ketika kita menjalankan UI <em>test</em> Android, yang terjadi di belakangnya adalah, Android SDK akan membuat dua buah file APK. Yang pertama adalah APK aplikasi kita, kita sebut sebagai <em>app</em> APK, dan yang kedua adalah APK yang berisi semua test yang akan dijalankan beserta test runner nya, kita sebut sebagai <em>test</em> APK.</p><p>Kemudian sebuah program kecil bernama <strong>ADB</strong>, atau <a href="https://developer.android.com/studio/command-line/adb"><strong>Android Debug Bridge</strong></a>, yang merupakan <em>tools</em> bawaan Android SDK akan menjalankan dua buah perintah (<em>command</em>) : <strong><em>push</em></strong>, di mana ADB akan meng-copy dua APK tadi ke device tempat tes akan dijalankan, dan <strong><em>install</em></strong>, di mana ADB akan meng-<em>install</em> kedua APK di <em>device</em> tersebut.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0A53mQD7NmMNLotS" /><figcaption>Gambar 13. Menjalankan Instrumentation Test</figcaption></figure><p>Setelah kedua APK terpasang, ADB akan menjalankan perintah berikutnya yaitu <strong><em>shell</em></strong>, yang berarti ADB akan mengakses <em>terminal</em> milik <em>device</em> tempat tes kita dijalankan, karena pada dasarnya Android sendiri adalah sebuah sistem operasi Linux.</p><p>Kemudian, di <em>terminal</em> tersebut, akan dijalankan sebuah aplikasi bernama <a href="https://developer.android.com/reference/android/app/ActivityManager"><strong>AM</strong></a>, atau <a href="https://developer.android.com/reference/android/app/ActivityManager"><strong>Activity Manager</strong></a>, dan AM akan menjalankan sebuah perintah, <strong><em>instrument</em></strong>, yang berarti akan menjalankan <em>instrumentation test</em> untuk kedua APK yang baru kita <em>install</em> tadi.</p><p>Dalam serangkaian tes tersebut bisa ada beberapa<em> test class</em>, dan untuk setiap <em>class</em>, bisa ada beberapa <em>test case</em>, dan untuk diingat, satu perintah adb shell am instrument … tadi, akan dijalankan untuk <em>semua</em> <em>test case</em>. Bukan<em> setiap test case.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AISjeiBpQpbiC0xA" /><figcaption>Gambar 14. Sebuah Testcase Crash</figcaption></figure><p>Pada gambar 14, dalam sebuah skenario, ada sebuah<em> test case, testA</em>, yang membuat <em>app</em> APK <em>crash</em> dan tes tersebut gagal. Di dalam antriannya, masih ada beberapa <em>test case </em>lain yang menunggu untuk dijalankan, apa yang terjadi berikutnya?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3kL_k2uzzGzR0bLt" /><figcaption>Gambar 15. Test Case Berikutnya Ikut Gagal</figcaption></figure><p>Karena perintah am instrument... tadi dijalankan untuk semua <em>test case</em>, ketika tiba giliran <em>testB</em> akan dijalankan, karena <em>app</em> APK nya sudah dalam keadaan <em>crash</em>, maka yang terjadi adalah <em>testB</em> akan ikut gagal, meskipun sebenarnya bisa saja <em>testB</em> lolos, hal yang sama akan terjadi di setiap antrian berikutnya.</p><h4>Test Isolation</h4><p>Pada <em>test isolation</em>, perintah am instrumentation... akan dijalankan untuk setiap <em>test case</em>, yang artinya setiap <em>test case</em> akan memiliki akses terhadap satu <em>instance app</em> APK dan terisolasi dari <em>test case</em> lainnya.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HOn5UkRMCklvFX2e" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FaiIeCsS8EEdErvP" /><figcaption>Gambar 16. Isolated Test</figcaption></figure><p>Jadi ketika ada sebuah <em>test case </em>yang menyebabkan <em>app</em> APK menjadi <em>crash</em>, karena setiap <em>test case </em>memiliki <em>instance app</em> APK masing-masing, maka <em>test case </em>berikutnya tidak akan terpengaruh, karena ia akan menjalankan<em> instance app</em> APK milik dia sendiri.</p><h4>Test Reporting</h4><p>Karena kami sudah tidak menggunakan Firebase Test Lab lagi, maka kami harus membuat sistem<em> test reporting </em>sendiri, untungnya hal tersebut disediakan oleh Spoon dan dapat diintegrasikan dengan baik dengan Jenkins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V1gxagMDPJWyQlNx" /><figcaption>Gambar 17. Spoon Test Reporting Level 1</figcaption></figure><p>Ketika serangkaian UI <em>test</em> sudah dijalankan, Spoon akan membuat<em> test report </em>berupa sejumlah <em>file html, css,</em> dan <em>javascript</em> di sebuah direktori. Direktori ini kemudian oleh Jenkins akan diarsipkan dan dapat diakses di halaman depan <em>job</em> kami.</p><p><em>Level</em> pertama <em>test report</em>-nya akan memperlihatkan beberapa <em>bar</em> sejumlah <em>device</em> yang digunakan pada <em>test sharding</em>, pada gambar 17, terlihat ada 3 <em>device</em> yang digunakan. dalam setiap <em>bar</em>, ada beberapa blok yang menandakan <em>test case </em>yang dijalankan di tiap <em>device</em>. Blok hijau menandakan test yang sukses, merah yang gagal, dan abu-abu yang diabaikan (<em>ignored</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YCrTgfFWE-TiCj97" /><figcaption>Gambar 18. Spoon Test Reporting Level 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VJVH40lteeTUb4rs" /><figcaption>Gambar 19. Informasi LogCat di Salah Satu Test Case</figcaption></figure><p>Setiap blok <em>test case</em> akan mengarahkan pada informasi yang lebih detail mengenai <em>test case</em> tersebut, seperti <em>failed cause, logcat, </em>dan <em>instrumentation logs.</em></p><h4>Concurrent Test Run</h4><p>Kemampuan lain di sistem CI/CD kami yang baru adalah <em>concurrent test run</em>, artinya kami dapat menjalankan <em>job test runner</em> tanpa perlu menunggu <em>job test runner </em>lain selesai terlebih dulu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5Wqhg7y-V4zBQ-je" /><figcaption>Gambar 20. Concurrent Test Run</figcaption></figure><p>Di sistem CI/CD yang baru, terdapat satu <em>job</em> bertipe <a href="https://jenkins.io/doc/book/pipeline/multibranch/"><strong><em>multibranch pipeline</em></strong></a>, bernama PR. Job PR ini, sesuai namanya, bertugas untuk menjalankan tes untuk <em>pull request </em>dari GitHub Vidio Android.</p><p>Ketika ada pair engineer yang ingin mencoba sebuah kode namun tidak ingin mengubah kode yang ada di <em>branch master</em>, maka mereka dapat membuat sebuah <em>branch</em> sendiri dan membuat sebuah <em>pull request</em> untuk <em>branch</em> mereka. Jenkins kemudian akan mendeteksi otomatis akan <em>pull request</em> yang baru dibuat tersebut, kemudian membuat <em>job</em> sendiri dengan format “PR-x” dimana “x” adalah nomor<em> pull request </em>di GitHub. <em>Pair engineer</em> tadi kemudian dapat menjalankan <em>test</em> untuk <em>branch</em> mereka tanpa harus berbagi <em>resource</em> dengan<em> job master</em>.</p><p>Seperti halnya <em>job master</em>, job PR akan menggunakan 4 device yang berupa 3 smartphone dan 1 tablet.</p><h3>Time Comparison Between Old and New CI/CD</h3><p>Setelah selesai membangun sistem CI/CD yang baru, kami kemudian melakukan pengukuran waktu yang dibutuhkan untuk menjalankan serangkaian tes dan membuat <em>artifact</em>.</p><h4>Time Needed to Run The Tests</h4><p>Kami membandingkan waktu yang dibutuhkan untuk menjalankan satu<em> job master</em> di CI/CD baru dibandingkan dengan job-job yang relevan di CI/CD lama.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3JrRV3pWXBiuqUhFSb7Wg.png" /></figure><p>Di sistem CI/CD yang lama, karena <em>job</em> untuk menjalankan<em> unit test </em>dan UI <em>test</em> terpisah, kami menjumlahkan waktunya, yang besarnya kurang lebih sekitar <strong>19 menit</strong>.</p><p>Sedangkan untuk CI/CD yang baru, karena CI/CD yang lama hanya menjalankan <em>medium test</em> untuk UI <em>test-</em>nya, kami juga hanya memasukkan waktu yang dibutuhkan untuk menjalankan <em>medium test</em>. Ketika dijumlah, besarnya sekitar <strong>10 menit</strong>. Untuk UI test di modul <em>platform</em> dan <em>tv</em> hanya baru ada di CI/CD yang baru, yang membutuhkan waktu <strong>2 menit</strong>.</p><p>Kami menambah tes baru untuk modul <em>platform</em> dan <em>tv</em>, namun waktu yang dibutuhkan lebih sedikit dibandingkan CI/CD yang lama.</p><h4>Time Needed to Build Artifacts</h4><p>Kami melakukan komparasi antara <em>job artifact debug</em> dan <em>artifact proguarded </em>antara CI/CD yang baru dengan yang lama.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fzUtdMYa8vpXiq7c9a9uwg.png" /></figure><p>hasilnya, di sistem CI/CD yang baru kami membutuhkan waktu yang sama dengan CI/CD yang lama. Namun kami masih bisa mereduksinya lagi karena setelah kami periksa, di CI/CD yang baru, sebagian besar waktu habis untuk mengunduh <em>dependency</em> <a href="https://docs.gradle.org/current/userguide/gradle_wrapper.html">gradlew</a> ketika <em>job artifact debug</em> &amp; <em>proguarded</em> dijalankan. Hal ini bisa diatasi dengan melakukan <em>dependency caching</em> ketika kami menjalankan <em>job</em> “<em>create image</em>” untuk membuat <em>image</em> baru.</p><p>Apakah kami puas dengan sistem CI/CD kami yang baru? Ya dan Tidak.</p><p>Ya karena waktu yang dibutuhkan untuk menjalankan tes menjadi berkurang yang otomatis berefek meningkatnya produktivitas kami.</p><p>Tidak, karena kami yakin sistem CI/CD kami yang baru ini masih bisa dioptimalkan lagi performanya.</p><p>Akhir kata, semoga tulisan ini bermanfaat dan dapat menambah wawasan bagi anda yang ingin mengetahui bagaimana sistem CI/CD tim Vidio Android dibangun dan bekerja.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f279c8d9b7e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vidio/membangun-vidio-android-ci-cd-dengan-jenkins-google-compute-engine-dan-genymotion-cloud-1f279c8d9b7e">Membangun Vidio Android CI/CD dengan Jenkins, Google Compute Engine dan Genymotion Cloud</a> was originally published in <a href="https://medium.com/vidio">Karena Kita Vidio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mengulik Reactive Programming di Android — bagian 1]]></title>
            <link>https://medium.com/@rohmanhakim/mengulik-reactive-programming-di-android-bagian-1-916b111c5597?source=rss-ee3cbad5a4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/916b111c5597</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Muhammad Arif Rohman Hakim]]></dc:creator>
            <pubDate>Thu, 05 Jan 2017 09:59:42 GMT</pubDate>
            <atom:updated>2019-07-17T02:13:18.414Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*17XfDRSmyLwpsukp99d2Fw.jpeg" /></figure><p>Bagi pembaca yang seorang <em>front-end engineer</em>, baik <em>web</em> maupun <em>mobile</em>, mungkin sering bertanya-tanya kenapa belakangan ini banyak pihak berkoar-koar tentang <em>Reactive Programming </em>(RP)<em>, </em>beserta beberapa nama <em>library</em> seperti <em>Rx</em>.</p><p>Dalam profesi saya sebagai <em>product</em> <em>engineer </em>aplikasi Android di Go-Jek, saya mendapat kesempatan mempelajari dan menggunakannya dalam beberapa proyek, dengan bantuan rekan-rekan saya yang sangat suportif seperti <a href="https://medium.com/u/ce1e45f5127d">salis muhammad</a> ketika saya mengalami kesulitan.</p><p>Seperti bahasa pemrograman atau <em>framework </em>baru<em>, </em>belajar RP adalah hal yang sulit. Salah satunya, ketika kita baru mengenal RP, kita langsung disodori berbagi macam jargon baru yang asing. Untuk itu, dalam postingan ini saya akan jabarkan jargon-jargon tersebut secara berurutan dari hal yang paling dasar.</p><p>Mari kita mulai dengan teori.</p><h3><strong>Apa itu Reactive Programming</strong></h3><p><strong><em>I read about reactive programming definition all over the internet but all these complicated words gave me headache, geez…</em></strong></p><p>Hal tersulit dari RP sebenarnya adalah jika kita datang dari dunia pemrograman imperatif dan mencoba mengubah pola pikir kita menjadi <em>reactive thinking</em>.</p><p>Dari semua referensi yang menjelaskan tentang definisi RP, definisi yang paling memuaskan bagi saya adalah dari <a href="https://medium.com/u/3ba9db42812d">André Staltz</a>:</p><blockquote>Reactive programming is programming with asynchronous data stream.</blockquote><p>Ada dua istilah yang perlu kita telaah lebih lanjut: <em>asynchronous, </em>dan <em>stream.</em></p><p>Istilah<em> asynchronous</em> sebenarnya tidak asing jika anda lama berkutat di dunia <em>programming</em>. Jika anda merasa asing, silahkan membaca <a href="https://medium.com/@rohmanhakim/asynchronous-dalam-pemrograman-android-d4e5e1878065#.lyaosxdf4">postingan saya berikut </a>untuk mengetahui <em>asynchronous</em> di Android.</p><p><strong><em>Asynchronous</em></strong><em> </em><strong><em>data</em></strong><em> </em>adalah data yang tidak dapat diprediksi kapan ia dapat diterima. Contohnya ketika kita melakukan pemanggilan <em>request</em> ke suatu <em>endpoint</em> API. Di dalam pemrograman android, <em>OnClickListener() </em>adalah salah satu contoh <em>asynchronous event, </em>kita tidak dapat memprediksi kapan suatu tombol akan ditekan. Maka kita memberikan sebuah <em>event listener </em>yang akan mendeteksi <em>event </em>ketika sebuah tombol ditekan, misalnya.</p><p><strong><em>Stream</em></strong><em> </em>adalah sekumpulan data yang <strong>dikirim berurutan sesuai waktu</strong>. Ia seperti <em>array </em>yang ketambahan dimensi waktu. Jika di <em>array </em>biasa kita dapat mengambil <em>value</em> tiap anggotanya seketika saat array itu dibuat serta memiliki ukuran yang pasti, <em>stream </em>sedikit berbeda. Jika kita membuat sebuah <em>stream</em>, kita dapat mengiriminya <em>value</em> setiap saat sebanyak mungkin sampai kita menutup <em>stream</em> itu. Proses mengirim value ke stream tersebut disebut <strong><em>emitting, </em></strong>sedangkan proses menunggu value dikirim disebut <strong><em>subscribing</em></strong>.</p><p><strong><em>“Reactive Thinking” </em>adalah Tentang Konsep Bahwa Hampir Segala Sesuatu adalah <em>Stream</em>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*DRnlWieKxi36OG5IgjTDog.jpeg" /></figure><p>Jika diilustrasikan, bayangkan sebuah perosotan di mana anda berdiri di atasnya beserta sekeranjang penuh berisi bola. Kemudian ada anak kecil di bawah dengan keranjang lain yang kosong. Anda ingin agar anak tersebut menerima bola dari atas dari anda, untuk kemudian dimasukkan ke keranjang yang satunya. Anda dapat menggelindingkan bola dari atas setiap saat, sebanyak yang anda mau, kemudian anak yang di bawah akan menunggu sampai bola terebut diterimanya untuk kemudian ia masukkan ke keranjang satunya.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*iLBArvNLfCBQUUrBrZbwRw.jpeg" /></figure><ul><li>Perosotan tersebut adalah sebuah <em>stream, </em>atau kalau di <strong>Rx</strong> disebut <strong><em>observable, </em></strong>yang berisi bola.</li><li>Anda di atas sedang melakukan <em>emitting</em> bola ke prosotan tersebut.</li><li>Sedangkan<strong><em> </em></strong>anak yang menerima bola di bawah adalah <strong><em>observer</em></strong> yang sedang melakukan <em>subscribing</em><strong><em> </em></strong>terhadap perosotan tersebut untuk bola yang datang<strong><em>.</em></strong></li><li>Seluruh proses <em>observer-</em>melakukan-<em>subscribing-</em>terhadap-<em>observable</em> ini disebut <strong><em>subscription</em></strong></li></ul><p>Jika digambarkan dalam bentuk diagram maka kira-kira berbentuk seperti berikut:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*cAAj9VQ6iip8WevUASBNZw.png" /><figcaption>Diagram untuk stream bola</figcaption></figure><ul><li>Lingkaran menggambarkan value (bola) yang di-<em>emit</em> ke dalam <em>stream </em>(perosotan)</li><li>Anak panah menunjukkan arah urutan <em>stream</em> tersebut. <em>Value-value</em> yang di-<em>emit </em>ke <em>stream</em> tersebut berurutan sesuai waktu dari yang pertama di-emit berada di pangkal anak panah menuju ke ujung anak panah.</li><li>Jarak antar <em>value</em> tersebut adalah jarak waktu ketika mereka di-<em>emit</em>.</li><li>Garis yang melintang di dekat ujung anak panah menandakan <em>stream</em> tersebut sudah selesai (<em>closed</em>/<em>completed</em>).</li></ul><p>Dalam RP, diagram ini disebut <strong><em>Marble Diagram</em></strong>.</p><p>Jika kita anggap bola-bola yang kita kirim adalah sebuah integer, kemudian kita mengirimkannya dengan urutan pertama 4, kemudian ada jeda sekitar beberapa detik, dilanjutkan 6,2,1 lalu terakhir 7 , maka diagramnya akan berbentuk:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*TDxtK3ozRDUh-xKFHsQRtQ.png" /><figcaption>Diagram untuk stream integer</figcaption></figure><p>Jika kita lihat, <em>value-value</em> yang kita <em>emit</em> tersebut tidak dapat kita prediksi kapan dapat diterima, dengan kata lain <strong><em>asynchronous</em></strong><em>. </em>Kita berurusan dengan sebuah <em>asynchronous data stream.</em></p><p><strong>Transformasi Data</strong></p><p>Hal yang menarik dari <em>stream</em> adalah<em> </em>kita dapat melakukan transformasi terhadap data yang dikirim ke dalam <em>stream </em>ke dalam bentuk yang kita inginkan. Hal ini tidak berhenti di sini, kita kemudian dapat menyambungkan stream tersebut dengan stream lain berikutnya yang dapat melakukan hal yang sama. Dalam hal ini, kita telah melakukan <strong><em>chaining</em></strong> antar <em>stream.</em></p><p>Sebuah contoh kasus, sebuah aplikasi di mana user dapat memasukkan serangkaian angka ke dalam <em>EditText</em>. Kita ingin menampilkan berapa jumlah angka genap dalam serangkaian <em>text</em> tersebut secara langsung ketika user mengetik. Bagaimana kita dapat melakukannya?</p><p><strong><em>Operator</em></strong> akan mempermudah kita. Anggap user tersebut memasukkan rangkaian angka “8394126”. Setiap user tersebut mengetik sebuah angka di <em>EditText</em>, proses itu adalah sebuah <em>event</em> yang dapat di-<em>emit</em> ke dalam <em>stream</em>. Sehingga jika digambarkan dalam diagram :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*fw3OJT4EJXBexZhPL4zSSQ.png" /><figcaption>Diagram stream untuk deteksi angka genap</figcaption></figure><p>Fungsi yang ada di dalam kotak kuning disebut operator. Operator akan melakukan transformasi sebuah <em>stream</em>, dengan memasukkan fungsi sebagai sebuah parameter.</p><ol><li><a href="http://reactivex.io/documentation/operators/map.html"><strong>map()</strong></a><strong> </strong>— Gampangnya map() seperti “<em>for each</em>” <em>loop</em>. Ia akan melakukan <em>loop</em> ke sebuah <em>stream</em>, kemudian untuk setiap <em>value</em>, ia akan melakukan transformasi ke sebuah <em>value</em> yang baru. Operator ini membutuhkan masukan berupa sebuah fungsi yang berisi bagaimana transformasi <em>value</em> itu dilakukan.</li><li><a href="http://reactivex.io/documentation/operators/filter.html"><strong>filter()</strong></a><strong> </strong>— filter() membutuhkan parameter berupa fungsi kriteria. Sama halnya seperti map(), operator filter() akan melakukan <em>loop</em> ke sebuah <em>stream</em>. Bedanya filter() tidak akan mengikutsertakan <em>value</em> yang tidak sesuai fungsi kriteria.</li><li><a href="http://reactivex.io/documentation/operators/reduce.html"><strong>reduce()</strong></a><strong> </strong>— reduce() akan mengambil <em>value</em> pertama yang di-<em>emit</em> sebuah <em>stream</em> kemudian mengambil lagi seterusnya sampai <em>value</em> terakhir yang di-<em>emit</em>, kemudian ia akan menghasilkan sebuah <em>value</em> terakhir. Operator reduce() membutuhkan parameter berupa fungsi untuk melakukan akumulasi semua <em>value</em> tadi.</li></ol><p>Operator map(), filter(), dan reduce() ini sebenarnya berasal dari dunia <em>functional programming</em>. Anda dapat mempelajarinya lebih lanjut di <a href="http://cryto.net/~joepie91/blog/2015/05/04/functional-programming-in-javascript-map-filter-reduce/">sini</a>.</p><p>Perlu diperhatikan bahwa, <strong>operator tidak memodifikasi <em>stream</em>, namun menghasilkan <em>stream</em> baru</strong>. Keempat <em>stream</em> di contoh di atas adalah empat <em>stream</em> yang berbeda. Hal ini juga berasal dari dunia <em>functional programming</em> yang disebut <a href="https://medium.com/javascript-scene/the-dao-of-immutability-9f91a70c88cd#.s6sob6rbz"><strong><em>immutability</em></strong></a>.</p><h3>Kenapa Reactive Programming</h3><p><strong><em>Okay, I got reactive programming and stream, but why should i give a damn about it?</em></strong></p><p>Salah satu prinsip saya ketika bekerja dalam proyek <em>software</em> adalah sebelum memutuskan untuk memakai teknologi<em>/framework/library </em>tertentu, saya harus tahu <strong>alasan kenapa ia harus dipakai</strong>. Keuntungan apa yang akan saya peroleh dengan memakainya? Apa kelebihannya dibandingkan dengan metode lain yang sama-sama menyelesaikan problem yang sama?</p><p>Saya skeptis dengan RP ketika pertama kali saya dihadapkan dengan sebuah proyek yang mengimplementasikan library <a href="https://github.com/ReactiveX/RxJava"><strong>RxJava</strong></a>. Berangkat dari dunia <em>imperative</em>, saya merasa bahwa tanpa RP-pun saya bisa menyelesaiakan sebagian besar permasalahan dalam pembuatan <em>software.</em></p><p><em>Turns out, i’m right…</em></p><p><em>…and wrong.</em></p><p>RP adalah salah satu hal yang menyenangkan dilakukan dalam menyelesaikan beberapa problem pembuatan <em>software</em> ketika kita sudah tahu untuk apa ia dibuat.</p><p><strong><em>Reactive Programming</em> Membantu Kita Menyelesaikan Permasalahan <em>Real-Time</em> UX yang Kompleks</strong></p><p>Dalam hal ini kita harus menilik sejarah.</p><p>Satu dekade yang lalu, interaksi manusia-komputer sebagian besar berupa proses user mengirim data <em>form</em>, kemudian <em>server</em> akan mengolah data tersebut, untuk selanjutnya dikirim kembali ke <em>user</em>.</p><p>Namun, jika melihat belakangan ini, kebutuhan manusia akan respon informasi yang cepat dari komputer meningkat. Aplikasi <em>real-time</em> mendominasi. <em>Front-end</em> telah berevolusi menjadi interaksi berat yang harus berurusan dengan banyak data secara <em>real-time:</em></p><ul><li>Ketikan di sebuah <em>chatbox</em> akan memicu notifikasi untuk <em>user</em> lain di <em>device</em>-nya,</li><li>Ketikan tulisan di halaman <em>new story</em> Medium akan memicu <em>save</em> di <em>database,</em></li><li>Sebuah halaman <em>dashboard</em> harus melakukan <em>log tracking</em> dari <em>server</em> dan memvisualisasikannya menjadi diagram,</li><li>dan sebagainya.</li></ul><p><em>Front-end</em> mulai mengenal dimensi baru bernama “waktu” saat mengolah data <em>asynchronous</em>. Kita membutuhkan alat untuk berurusan dengannya secara benar. Saat itulah konsep <em>stream/observable</em> dan RP lahir.</p><p><strong><em>Wait, aren’t there bunch of Callbacks, Listeners, or Event Buses to handle asynchrony in Android? Why don’t we use these instead?</em></strong></p><blockquote>We haven’t used <a href="http://square.github.io/otto/">Otto</a> (an event bus library for Android) in a year and a half, if not more…We think we found a better mechanism. That mechanism is…RxJava where we can create a much more specific pipeline of events than a giant generic bus that just shoves any event across it.</blockquote><blockquote>— Jake Wharton, in <a href="http://fragmentedpodcast.com/episodes/6/">Fragmented podcast, Episode 6, 50:26–51:00</a></blockquote><p>Sebagai contoh saya akan berikan kasus di mana kita ingin membuat aplikasi untuk mendeteksi <em>double tap</em> di Android. Aplikasi tersebut harus menghitung berapa jumlah <em>tap</em> yang dilakukan <em>user</em> ketika ia melakukan <em>double tap</em> atau lebih (<em>triple tap</em>,<em> quadruple tap</em>, dst…).</p><p>Pertanyaannya bagaimana kita mendefinisikan “<em>double tap</em>” secara <em>imperative</em> di Android?</p><p>Well, solusi secara <em>reactive</em> akan memudahkan kita.</p><p>Dalam RP ada empat langkah dasar untuk menyelesaikan masalah :</p><ol><li>Buat model dengan <em>stream (observable)</em></li><li>Tentukan bentuk akhir <em>stream</em></li><li>Lakukan transformasi dengan operator bila perlu</li><li>Buat <em>observer</em> &amp; lakukan <em>subscribing</em> terhadap <em>stream</em></li></ol><p>Untuk memodelkan permasalahan tadi dengan <em>stream</em>, kita gunakan lagi <em>marble diagram</em>. Kita bisa membuat <em>stream</em> yang meng-<em>emit</em> “<em>tap</em>” <em>user</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*vZsA0Xgx0R5dAQGaeIwfKA.png" /><figcaption>Stream of taps.</figcaption></figure><p>Setiap lingkaran tersebut mewakili satu <em>tap event</em> dari <em>user</em>. Dengan <em>model</em> ini, kita bisa mendefinisikan “<em>double tap</em>” sebagai dua buah <em>event tap</em> yang memiliki jarak maksimal 1 detik.</p><p>Karena kita ingin menghitung jumlah <em>tap</em>, maka hasil akhir dari <em>stream</em> yang kita butuhkan adalah <em>stream of Integer</em>.</p><p>Dengan operator, maka proses transformasi dapat kita gambarkan sebagai berikut:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*JTzUTK6wCoBgBP_LHXM0Bg.png" /></figure><p>Operator buffer(x.debounce(1 second)) akan melakukan transformasi <em>stream</em> awal (<em>stream</em> x) ketika ada dua atau lebih <em>value</em> yang di-<em>emit</em> berdekatan (berjarak kurang dari 1 detik), akan menghasilkan <em>stream</em> baru dengan <em>value</em> berupa list dari <em>value-value</em> yang berdekatan tadi.</p><p>Operasi berikutnya adalah mengubah <em>stream</em> kedua dari bentuk <em>stream of list of taps</em>, menjadi <em>stream of integer</em>. <em>Integer</em> tersebut berupa <em>size </em>dari<em> list of taps </em>tadi. Kemudian operasi terakhir adalah melakukan operasi filter() untuk <em>value</em> yang bernilai 2 atau lebih.</p><p>Implementasi kode dari seluruh kasus ini kira-kira sebagai berikut:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc99dae2d594708aa9a2e13cf5740e23/href">https://medium.com/media/bc99dae2d594708aa9a2e13cf5740e23/href</a></iframe><p>Dan hasilnya kira-kira sebagai berikut:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*mWpGp1MUbfnbIkpp7FOtxg.gif" /><figcaption>Multiple taps app</figcaption></figure><p><strong><em>But, why the heck would i create some double tap app in real life? Show me actual implementation!</em></strong></p><p>Mari kita terjun langsung ke dalam masalah di dunia nyata.</p><p>Sebuah aplikasi membutuhkan halaman untuk melakukan validasi <em>form</em> registrasi dengan ketentuan sebagai berikut:</p><ul><li>Dalam <em>state</em> (keadaan) <em>default</em>, <em>form</em> memiliki 3 <em>field</em> untuk <em>email</em>, <em>password</em>, dan konfirmasi <em>password</em>, serta sebuah tombol “<em>Submit</em>”</li><li>Dalam <em>state</em> <em>default</em>, tombol “<em>Submit</em>” di-<em>disable</em>.</li><li><em>User</em> harus mengisi email yang belum terdaftar, jika sudah terdaftar tampilkan notifikasi peringatan.</li><li>Pengecekan email hanya dilakukan ketika user mengetikkan lebih dari 3 karakter di <em>field</em> email.</li><li>User harus mengisi <em>password</em> sepanjang minimal 6 karakter, jika kurang, tampilkan notifikasi peringatan.</li><li>User harus mengisi konfirmasi <em>password</em>, jika tidak sama dengan <em>password</em> yang sudah diisi, tampilkan notifikasi peringatan.</li><li>User harus mengisi semua <em>field</em>, jika masih ada yang kosong, tombol “Submit” tidak akan di-<em>enable.</em></li><li>Jika semua ketentuan sudah terpenuhi, <em>enable</em> button “Submit”.</li></ul><p>Bagaimana kita cara kita menyelesaikan permasalahan ini tanpa RP? Pendekatan yang kita lakukan mungkin seperti ini:</p><ul><li>Membuat tiga <em>TextWatcher</em> untuk masing-masing <em>field.</em></li><li>Membuat <em>flag</em> untuk me-<em>monitor</em> ketiga <em>field</em> tersebut <em>valid</em> atau tidak.</li><li>Setiap user mengetik email, panggil API kemudian lakukan validasi terhadap email, update <em>flag</em> <em>valid</em> email, dan cek <em>flag</em> <em>valid</em> untuk <em>field</em> yang lain.</li><li>Setiap user mengetik <em>password</em>, cek validasi, update <em>flag</em> <em>valid</em> <em>password</em>, cek validasi <em>field</em> konfirmasi <em>password</em>, dan cek <em>flag valid</em> untuk <em>field</em> yang lain.</li><li>Setiap <em>user</em> mengetik konfirmasi <em>password</em>, cek validasi, <em>update flag valid</em> konfirmasi <em>password</em>, dan cek <em>flag</em> <em>valid</em> untuk <em>field</em> yang lain.</li><li>Jika semua <em>flag</em> bernilai <em>valid</em>, <em>enable</em> tombol “<em>Submit</em>” dan sebaliknya.</li></ul><p>Jika dilihat dalam kode, maka kira-kira akan seperti ini:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/131ec8edf0d40337f20c5785a7835906/href">https://medium.com/media/131ec8edf0d40337f20c5785a7835906/href</a></iframe><p>Implementasi tanpa RP ini mudah dipahami, tapi:</p><ul><li>Ada tiga <em>TextWatcher</em> yang semuanya memiliki <em>method</em> kosong hanya untuk memenuhi syarat.</li><li>Menyimpan <em>state </em>untuk<em> valid</em> tidaknya suatu <em>field</em> di beberapa <em>flag</em> yang tersebar di beberapa fungsi <em>asynchronous</em>. Di mana hal ini dapat menyebabkan <em>bug</em> sulit dicari.</li><li>Pada field email, aplikasi akan melakukan pemanggilan API <strong>setiap user mengetik satu huruf</strong>. Bukannya menunggu sampai <em>user</em> berhenti mengetik.</li><li>Kode untuk mengupdate UI dan <em>logic</em> bercampur di banyak tempat.</li></ul><p>Ada cara yang lebih baik. Mari kita selesaikan masalah ini dengan RP.</p><p>Langkah-langkah yang akan saya jelaskan berikut akan disertai kode dari <em>RxJava</em>, <em>RxAndroid</em> dan <em>RxBinding</em>. Namun jangan khawatir jika anda masih asing. Tujuan kita disini adalah mengetahui bagaimana RP menyelesaikan sebuah masalah.</p><p>Dari aturan-aturan untuk aplikasi registrasi kita tadi, mari kita mulai dengan aturan untuk validasi email:</p><p><em>(1) User harus mengisi email yang belum terdaftar, apabila apabila sudah terdaftar tampilkan notifikasi peringatan.</em></p><p><em>(2) Pengecekan email hanya dilakukan ketika user mengetikkan lebih dari 3 karakter di field email.</em></p><p>Dari aturan di atas kita bisa menyimpulkan kalau kita ingin hasil akhir dari proses ini adalah <strong><em>boolean</em> yang menyatakan apakah email <em>user</em> sudah ada atau belum</strong>. Maka kita ingin hasil akhir <em>stream</em> kita nanti adalah s<em>tream of boolean</em>.</p><p>Sebagai tambahan dalam aturan ke (2) kita juga ingin agar aplikasi tidak melaukan pemanggilan API setiap <em>user</em> mengetik karakter. Kita ingin agar ia hanya melakukannya jika <em>user</em> berhenti mengetik minimal selama 100ms.</p><p>Untuk menyelesaikan ini, kita akan membuat dua buah <em>stream</em>. <em>Stream</em> pertama berupa <em>stream of string</em> untuk melakukan <em>trigger</em> kapan saat yang tepat untuk melakukan pemanggilan API. Stream kedua berupa <em>stream of boolean</em> berisi apakah email yang diketik <em>user</em> sudah dipakai.</p><p>Kita mulai dengan <em>stream</em> pertama.</p><p>Kita bisa memodelkan ketikan user menjadi <em>stream</em> dengan diagram sebagai berikut:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*q314hssKaXo8x3tqt70XVA.jpeg" /><figcaption>Steam untuk ketikan email “ab@cd.com”</figcaption></figure><p><em>Stream</em> ketikan user tersebut berupa stream of <em>CharSequence</em>, karena itu kita harus mengubahnya menjadi <em>string</em> dulu, hal ini bisa kita lakukan dengan operator map():</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*_OgspoQLt2gwqzDzjUEZiQ.png" /></figure><p>Langkah selanjutnya, kita ingin agar pengecekan hanya dilakukan jika <em>user</em> mengetikan lebih dari 3 karakter. Kita bisa menggunakan operator filter(). Ketika user mengetik “ab@”, operator filter() akan menghasilkan <em>stream</em> dengan isi kosong :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*PDfa8OHBCz2khlxt-UTeNQ.png" /></figure><p>Dan ketika <em>user</em> mengetik “ab@cd.com”, karena karakternya lebih dari 6, maka semua <em>string</em> tersebut akan lolos:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*QegFSjN9l6jnrFQfKZz_YA.png" /></figure><p>Selanjutanya kita ingin agar aplikasi hanya melakukan pemanggilan API ke <em>backend</em> ketika <em>user</em> berhenti minimal 100ms saat mengetik. Kita bisa melakukan <em>chaining</em> operator debounce().</p><p>debounce() hanya akan mengembalikan <em>value</em> yang memiliki jarak waktu minimal tertentu dengan <em>value</em> sesudahnya. Jadi jika kita menggambarkan aturan kita tadi dengan diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*5y2RaecW82EQcsxbNI3kjg.png" /></figure><p>Dalam diagram tersebut, ketika user mengetik karakter “.” dilanjutkan “c” jarak waktunya tidak ada 100ms sehingga “.” tidak di-<em>return</em>. Sedangkan ketika <em>user</em> mengetik “c” dilanjutkan dengan “0” <em>user</em> telah melakukan jeda lebih dari 100ms, sehingga karakter “c” di-<em>return</em>, begitu juga dengan “o” dan “m”. Aplikasi akan melakukan pemanggilan API sebanyak 3 kali, yaitu ketika user berhenti di karakter “c”, “o” dan “m”.</p><p>Dari semua langkah di atas, hasil sementara dari <em>stream</em> ini adalah :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90615666b3893772a7902b7e4cc1071f/href">https://medium.com/media/90615666b3893772a7902b7e4cc1071f/href</a></iframe><p>Langkah berikutnya, dari <em>value</em> yang lolos dari semua operator tadi kita jadikan <em>trigger</em> untuk melakukan pemanggilan API di <em>stream</em> kedua.</p><p>Dalam hal ini, lagi-lagi <em>RxJava</em> sangat membantu kita. Ia mengijinkan kita untuk membuat data <em>response</em> hasil <em>Retrofit</em> berupa <em>stream</em>, sehingga kita bisa mengolahnya dengan operator. Awesome!</p><p><em>Interface</em> <em>Retrofit</em> untuk API kita bisa dibuat seperti berikut:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/268af1dc1044dea98117dfe6185276a9/href">https://medium.com/media/268af1dc1044dea98117dfe6185276a9/href</a></iframe><p>Dalam <em>endpoint</em> /emails contoh tersebut, data <em>response</em>-nya berupa <em>list of all emails</em>, jadi kita harus melakukan pengecekan apakah email sudah ada atau belum di <em>client</em>.</p><p>Untuk sementara mari kita beranjak sejenak dari <em>stream</em> pertama yang merupakan hasil <em>filter</em> dan untuk melakukan <em>triggering</em> tadi. Kita beralih ke <em>stream</em> kedua, <em>stream</em> hasil pengecekan <em>input</em> email <em>user</em>.</p><p>Seperti biasa langkah awal adalah memodelkan <em>stream</em> menjadi diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*ixWDPtAOzGlx8ji04DIqOg.png" /><figcaption>Stream of list of emails</figcaption></figure><p>Bukan seperti bentuk yang kita inginkan untuk melakukan pengecekan input. Kita ingin bentuknya berupa <em>stream of email</em>, bukan <em>list-</em>nya. Operator flatMap() akan menolong kita:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*H4rbEwczqT9Y6ys-ULzkcQ.png" /><figcaption>Mengubah stream of list of emails menjadi stream of email</figcaption></figure><p><strong>flatMap() </strong>— akan melakukan transformasi dari <em>value</em> yang berupa <em>collection</em> (<em>Array, List</em>, dll) menjadi <em>value</em> berupa anggotanya, kemudian menggabungkannya menjadi satu <em>stream</em>.</p><p>Langkah terkahir dari <em>stream</em> ini adalah mengecek apakah <em>input</em> <em>user</em> ada di dalam <em>stream</em> ini. Kita dapat melakukannya dengan operator contains() :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*Lbfzfo1cflgEesG4__d-Lg.png" /></figure><p><strong>contains()</strong> — akan me-<em>return</em> <em>true</em> jika suatu <em>value</em> di-<em>emit</em> oleh sebuah <em>stream</em>, dan me-<em>return</em> <em>false</em> jika <em>stream</em> tersebut completed tanpa meng-<em>emit</em> <em>value</em> tersebut.</p><p>Bentuk pembuatan <em>stream</em> kedua ini dalam kode kira-kira sebagai berikut:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7eaf8a3902deb4dab6942305a6626553/href">https://medium.com/media/7eaf8a3902deb4dab6942305a6626553/href</a></iframe><p>Langkah terakhir adalah men-<em>trigger</em> checkIfEmailExistFromAPI() setelah membuat <em>stream</em> pertama. Kita tinggal memanggil fungsi tersebut di dalam operator flatMap() dari <em>stream</em> pertama. Sehingga implementasinya dalam kode kira-kira sebagai berikut:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb8960ed2d28b28c23d001fea6b9f284/href">https://medium.com/media/cb8960ed2d28b28c23d001fea6b9f284/href</a></iframe><p>Langkah selanjutnya setelah membuat <em>stream</em> adalah membuat <em>observer</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9864d71b3894043f4ceef508c71917aa/href">https://medium.com/media/9864d71b3894043f4ceef508c71917aa/href</a></iframe><p>Ketika <em>stream</em> selesai dan ketika terjadi <em>error,</em> aplikasi cukup mengeluarkan <em>log</em>. Fungsi showEmailExistAlert() akan menampilkan <em>TextView</em> berdasarkan output <em>boolean</em> dari <em>stream</em> yang kita buat:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfa36db9ee907f2179f6a3bcd50a200c/href">https://medium.com/media/dfa36db9ee907f2179f6a3bcd50a200c/href</a></iframe><p>Langkah terakhir adalah melakukan <em>subcribing</em> ke <em>stream</em> yang telah kita buat.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/346514d695ed9368032f650a50f952e3/href">https://medium.com/media/346514d695ed9368032f650a50f952e3/href</a></iframe><p>Dengan ini validasi email selesai. Kita tinggal melanjutkan ke <em>rule</em> aplikasi untuk <em>password</em>, konfirmasi <em>password</em>, dan <em>empty field</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZVGtaClLk6DtqUUyqRv44A.gif" /><figcaption>Validasi Email</figcaption></figure><p>Validasi <em>password</em> cukup sederhana, kita cukup menggunakan operator map() untuk mengubah input user menjadi <em>boolean</em>. Ketika panjang <em>password</em> kurang dari 6, <em>return true</em>. Untuk observer, kita buat mirip dengan validasi email.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c15b4f26b5a24eaebc68264f8b101ff9/href">https://medium.com/media/c15b4f26b5a24eaebc68264f8b101ff9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W2R4xbswdT4C49vBzCFBkg.gif" /><figcaption>Validasi Password</figcaption></figure><p>Untuk validasi konfirmasi <em>password</em>, kita ingin agar <em>trigger</em> terjadi baik ketika user mengetik di <em>field</em> <em>password</em> maupun di <em>field</em> konfirmasi <em>password</em>.</p><p>Untuk itu kita membutuhkan dua <em>stream</em> untuk masing-masing <em>field</em> tersebut, kemudian kita gabung dengan <em>operator </em><strong>merge()</strong> menjadi satu <em>stream</em>. Masing-masing <em>stream</em> tersebut sebelumnya akan mengapliaksikan operator map() untuk mengubah <em>charSequence</em> menjadi <em>string</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a94d5c329a9a679d1d47d419e2b065ed/href">https://medium.com/media/a94d5c329a9a679d1d47d419e2b065ed/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*g5iQvhqefdQllwT_YKdJHg.png" /><figcaption>Ilustrasi merge()</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g10WeEQdDehcizHoCjTxqw.gif" /></figure><p><em>Rule</em> berikutnya, kita ingin ketika ada <em>field</em> yang kosong atau ketika salah satu dari validasi email, <em>password</em>, dan konfirmasi <em>password</em> gagal, tombol <em>submit</em> akan di-<em>disable</em>.</p><p>Untuk merealisasikan hal tersebut, pertama, kita buat tiga buah <em>stream</em> untuk masing-masing <em>field</em> (email, <em>password</em>, dan konfirmasi <em>password</em>). Kemudian kita aplikasikan operator <strong>combineLatest()</strong> Operator tersebut akan mengambil <em>value</em> terakhir yang di-<em>emit</em> masing-masing <em>stream</em>, kemudian menggabungkannya menjadi satu <em>stream</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*PfXz8Hgnf3HN5P32I3zlEA.png" /></figure><p>Fungsi yang akan kita pakai dengan operator combineLatest() adalah</p><pre>emailEmpty || passwordEmpty || passwordConfirmationEmpty</pre><p>Dengan demikian, <em>stream</em> hasil combineLatest() hanya akan me-<em>return</em> <em>false</em> jika ketiga <em>stream</em> di atas me-<em>return</em> <em>false</em> semua.</p><p>Implementasi kodenya kira-kira sebagai berikut:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0dc9fe2f9a8d167b582805f803f450a/href">https://medium.com/media/c0dc9fe2f9a8d167b582805f803f450a/href</a></iframe><p>Terakhir, kita aplikasikan lagi operator combineLatest() untuk <em>stream</em> tadi dengan <em>stream</em> validasi email, <em>password</em> dan konfirmasi <em>password</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aac67ba82596408de6ee14499fd7a2a3/href">https://medium.com/media/aac67ba82596408de6ee14499fd7a2a3/href</a></iframe><p>Fungsi yang kita pakai untuk operator combineLatest() di atas adalah:</p><pre>!emailInvalid &amp;&amp; !passwordInvalid &amp;&amp; !passwordConfirmationInvalid &amp;&amp; !emptyFieldExist</pre><p>Sehingga hanya ketika semua <em>stream</em> meng-<em>emit</em> <em>false</em>, tombol <em>submit</em> akan di-<em>enable</em>.</p><p>Hasil implementasi dari <em>stream</em> ini berikut <em>observer</em>-nya kira-kira sebagai berikut:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e26d0d50eb0cb3a38f57a35a78c14a4/href">https://medium.com/media/4e26d0d50eb0cb3a38f57a35a78c14a4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*tEaZSGzorgypVjPoclZVCQ.gif" /></figure><p>Implementasi hasil akhir dari seluruh proses ini dapat dilihat di <a href="https://gist.github.com/rohmanhakim/9eaea79c1239c1829bd90f5671d16e46">sini</a>.</p><p>Solusi dari penggunaan <em>reactive programming</em> ini memang terlihat memusingkan dan memiliki banyak <em>line of code</em> (LOC). Hal ini sebenarnya dikarenakan tidak terdapatnya fitur <em>lambda expression</em> di Java 7. Beberapa developer Android yang expert seperti <a href="http://blog.danlew.net/">Dan Lew</a> menggunakan <a href="https://github.com/evant/gradle-retrolambda">retrolambda</a> dalam solusinya.</p><p>Di luar hal tersebut, solusi <em>reactive programming</em> ini menghilangkan kekurangan solusi <em>imperative</em> yang kita pakai sebelumnya.</p><p><em>Source code</em> dari aplikasi di postingan ini dapat dilihat di repositori saya <a href="https://github.com/rohmanhakim/android-reactive-demo">di sini</a>.</p><p><strong>Simpulan</strong></p><p><em>Reactive programming</em> memudahkan kita sebagai <em>developer</em> untuk menyelesaikan masalah <em>real-time</em> di ranah UI.</p><p><em>Reactive programming</em> tidak diciptakan untuk menggantikan <em>imperative programming</em>, namun lebih sebagai pelengkap.</p><p>Bagi anda yang masih bingung dengan kode-kode implementasi <em>RxJava</em>, di postingan berikutnya akan saya ajak untuk mempelajarinya dari hal dasar.</p><p>Terima kasih telah membaca postingan saya kali ini, semoga bermanfaat. Jika anda memiliki pertanyaan seputar postingan ini silahkan ajukan di kolom komentar. Saya dengan senang hati akan menjawab.</p><p>Terakhir, jika anda merasa bahwa postingan ini membantu anda, silahkan klik tombol 👏</p><p><em>Happy coding!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=916b111c5597" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronous dalam Pemrograman Android]]></title>
            <link>https://medium.com/@rohmanhakim/asynchronous-dalam-pemrograman-android-d4e5e1878065?source=rss-ee3cbad5a4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4e5e1878065</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Muhammad Arif Rohman Hakim]]></dc:creator>
            <pubDate>Wed, 07 Dec 2016 16:21:36 GMT</pubDate>
            <atom:updated>2018-10-02T13:30:59.830Z</atom:updated>
            <content:encoded><![CDATA[<p>Dalam postingan ini kita akan menelaah tentang konsep “<em>asynchronous”. </em>Apa maksudnya dan seperti apa penggunaannya.</p><p>Berangkat dari pengalaman saya sebagai seorang programmer <em>nubitol </em>dari kuliah, istilah <em>asynchronous </em>ini sering membuat saya <em>kelimpungan </em>ketika pertama kali mengenal pemrograman <em>mobile</em>. Apa ia sebenarnya?</p><h3><strong>Untuk mengerti <em>asynchronous, </em>langkah pertama adalah harus mengerti <em>synchronous, </em>lawan katanya</strong></h3><p><strong><em>Synchronous</em></strong> dalam pemrograman adalah sekumpulan <em>statement </em>kode yang dieksekusi secara berurutan. Dengan kata lain, tiap baris <em>statement </em>akan dieksekusi setelah <em>statement </em>sebelumnya sudah selesai dieksekusi.</p><p>Mari lihat contoh kasus.</p><p>Anggap saya ingin membuat sebuah aplikasi yang akan menunggah file ke sebuah user dari <em>back-end,</em></p><p>Untuk contoh ini, proses yang sebenarnya akan saya ganti dengan log :</p><pre>private void upload(){<br>   Log.<em>d</em>(&quot;test&quot;,&quot;Mengunggah file&quot;);<br>}</pre><pre>private void showNotification(){<br>   Log.<em>d</em>(&quot;test&quot;,&quot;File selesai diunggah&quot;);<br>}</pre><p>Jika method-method tersebut saya panggil secara <em>synchronous, </em>maka kira-kira akan berbentuk seperti berikut:</p><pre>@Override<br>protected void onCreate(Bundle savedInstanceState) {<br>    super.onCreate(savedInstanceState);<br>    setContentView(R.layout.<em>activity_main</em>);</pre><pre>    Button btnUpload = (Button) findViewById(R.id.<em>btn_upload</em>);<br><br>    btnUpload.setOnClickListener(new View.OnClickListener() {<br>        @Override<br>        public void onClick(View v) {<br>            upload();<br>            showNotification();<br>        }<br>    });<br>}</pre><p>Ketika user menekan tombol, Aplikasi akan mengeluarkan <em>log</em> output dengan urutan “Mengunggah file”, kemudian “File selesai diunggah”.</p><p>Tapi, bagaimana jika ternyata file yang diunggah user berukuran besar dan membutuhkan beberapa saat sampai program kita selesai mengunggah ?</p><p>Anggap file tersebut akan membutuhkan 2 detik untuk diunggah, saya ganti method <em>upload()</em> menjadi berikut :</p><pre>private void upload(){<br>   try {</pre><pre>       <em>// Saya ganti log dengan 2 detik delay </em><br>       Thread.<em>sleep</em>(2000);</pre><pre>   } catch (InterruptedException e) {<br>       e.printStackTrace();<br>   }<br>}</pre><p>Ketika dijalankan, program akan berhenti selama 2 detik, sebelum menampilkan notifikasi. Kemudian <em>logCat</em> akan menampilkan pesan berikut:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rkjdeCt-yAKg8BVV_VZg_w.png" /></figure><p>Bagaimana jika ternyata file yang akan diunggah membutuhkan waktu 1 jam atau lebih?</p><p>Beberapa proses dalam aplikasi membutuhkan tingkat pemrosesan yang berat seperti mengunggah/mengunduh file atau mengeksekusi query database. Proses <em>synchronous </em>akan menjalankan semua urutan tadi dalam 1 <em>thread </em>prosesor, sehingga program akan seolah-olah “membeku” karena menunggu prosesor untuk selesai mengeksekusi proses yang berat tadi.</p><p>Kita tidak ingin user disodori aplikasi yang “membeku” ketika melakukan hal-hal tersebut. Kita ingin agar user tetap dapat berinteraksi dengan hal-hal penting lain di aplikasi kita.</p><p><strong><em>Asynchronous</em></strong><em>, </em>sebaliknya, mengijinkan kita untuk menjalankan <em>statement </em>kode di <em>thread </em>lain di luar <em>thread</em> utama. Sehingga, ketika program mengeksekusi hal-hal berat di <em>thread</em> lain, user tetap dapat menjalankan proses lain di <em>thread</em> utama.</p><p>Di dalam pemrograman Android, kita dapat menggunakan <a href="https://developer.android.com/reference/android/os/AsyncTask.html"><strong><em>AsyncTask</em></strong></a><em> </em>untuk menjalankan proses secara <em>asynchronous</em>.</p><p>Jika saya ubah kode program saya tadi dengan <em>AsyncTask</em>, maka akan menjadi seperti berikut:</p><pre>private class UploadFileTask extends AsyncTask&lt;Void, Void, String&gt; {<br><br>    @Override<br>    protected String doInBackground(Void... params) {<br>        // <em>doInBackground() adalah tempat kita melakukan proses di thread lain</em><br>        upload();<br>        return null;<br>    }<br><br>    @Override<br>    protected void onPostExecute(String result) {<br>        // <em>onPostExecute akan dieksekusi setelah doInBackground selesai dieksekusi</em><br>        showNotification();<br>    }<br>}</pre><pre>@Override<br>protected void onCreate(Bundle savedInstanceState) {<br>    super.onCreate(savedInstanceState);<br>    setContentView(R.layout.<em>activity_main</em>);<br>    getSupportActionBar().setTitle(&quot;API Request Demo&quot;);<br><br>    Button btnUpload = (Button) findViewById(R.id.<em>btn_upload</em>);<br><br>    btnUpload.setOnClickListener(new View.OnClickListener() {<br>        @Override<br>        public void onClick(View v) {<br>            UploadFileTask uploadFileTask = new UploadFileTask();<br>            uploadFileTask.execute();<br>        }<br>    });<br>}</pre><p>Sekarang user dapat berinteraksi dengan hal lain di aplikasi kita tanpa perlu menunggu proses pengunggahan file selesai.</p><h3><strong>Kelas</strong> <strong>AsyncTask</strong></h3><p><em>AsyncTask</em> adalah salah satu kelas yang mengimplementasikan <em>asynchronous</em> di dalam pemrograman Android. Kelas lainnya yang sama-sama mengimplementasikan antara lain <a href="https://developer.android.com/reference/java/util/concurrent/Executor.html"><em>Executor</em></a><em>, </em><a href="https://developer.android.com/reference/java/util/concurrent/ThreadPoolExecutor.html"><em>ThreadPoolExecutor</em></a><em>, dan </em><a href="https://developer.android.com/reference/java/util/concurrent/FutureTask.html"><em>FutureTask</em></a>.</p><p><em>Method-method</em> yang tersedia di dalam <em>AsyncTask</em> adalah:</p><p><strong><em>onPreExecute() </em></strong>dieksekusi di <em>thread</em> utama sebelum proses <em>asynchronous </em>dieksekusi. <em>Method</em> ini biasanya digunakan untuk melakukan persiapan sebelum melakukan proses berat, misalnya seperti menampilkan <em>progress bar.</em></p><p><strong><em>doInBackground(Params…)</em></strong> dieksekusi di <em>thread</em> lain yang berjalan di belakang segera setelah <em>onPreExecute() </em>selesai dieksekusi. <em>Method</em> ini digunakan untuk menjalankan proses yang berat dan memakan waktu yang lama. <em>Value</em> hasil dari proses ini harus di <em>return</em> di <em>method</em> ini dan akan di-<em>passing</em> ke langkah terakhir. <em>Method</em> ini juga memperbolehkan kita menggunakan <strong><em>publishProgress(Progress…) </em></strong>untuk mengirim <em>progress</em> dari proses ini. <em>Value</em> dari <em>progress</em> tersebut akan dikirim ke <em>thread</em> utama di method <em>onProgressUpdate()</em>.</p><p><strong>onProgressUpdate(Progress…)</strong> dieksekusi di <em>thread</em> utama setelah pemanggilan <em>publishProgress(Progress…)</em>. <em>Method</em> ini digunakan untuk menampilkan segala bentuk <em>progress</em> ketika proses yang berlangsung di <em>doInBackground(Params…) </em>sedang dieksekusi. Misalnya, untuk menampilkan berapa persen file yang sedang diunggah.</p><p><strong>onPostExecute(Result)</strong> dieksekusi di <em>thread</em> utama setelah proses yang berlangsung di <em>doInBackground(Params…)</em> selesai dieksekusi. <em>Value</em> yang di <em>return</em> oleh <em>doInBackground(Params…)</em> akan di-<em>passing</em> ke <em>method</em> ini sebagai parameter.</p><h3><strong>Kesimpulan</strong></h3><p>Untuk merangkum semuanya, <em>synchronous</em> akan mengeksekusi proses secara berurutan satu sama lain di dalam satu <em>thread</em>. Setiap <em>statement</em> harus menunggu <em>statement</em> sebelumnya sampai selesai dieksekusi.</p><p>Sedangkan dalam <em>asynchronous</em> sebuah <em>statement</em> akan dieksekusi di <em>thread</em> terpisah, sehingga <em>statement</em> setelahnya tidak perlu menunggu sampai ia selesai dieksekusi.</p><p>Kita dapat mengimplementasikan hal ini ketika kita ingin agar seorang user dapat menghemat waktu dan melakukan interaksi dan hal lain di dalam sebuah aplikasi tanpa harus menunggu sebuah proses berat selesai dijalankan.</p><p>Terima kasih kepada anda yang membaca artikel ini, dan silahkan kirimkan komentar anda seputar pertanyaan atau hal lain yang ingin disampaikan mengenai artikel ini.</p><p><em>Happy coding!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4e5e1878065" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>