<?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 Sreehari Vasudevan on Medium]]></title>
        <description><![CDATA[Stories by Sreehari Vasudevan on Medium]]></description>
        <link>https://medium.com/@sreeharikv112?source=rss-500a950c8175------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*SD-Age6wdmIz3wR-zQw9rw.jpeg</url>
            <title>Stories by Sreehari Vasudevan on Medium</title>
            <link>https://medium.com/@sreeharikv112?source=rss-500a950c8175------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 08:17:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sreeharikv112/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[AI Agents and Building an Agent from Scratch]]></title>
            <link>https://sreeharikv112.medium.com/ai-agents-and-building-an-agent-from-scratch-74f3f31c9125?source=rss-500a950c8175------2</link>
            <guid isPermaLink="false">https://medium.com/p/74f3f31c9125</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai-model]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Sreehari Vasudevan]]></dc:creator>
            <pubDate>Thu, 16 Apr 2026 08:03:49 GMT</pubDate>
            <atom:updated>2026-04-16T08:25:26.114Z</atom:updated>
            <content:encoded><![CDATA[<p>The rapid rise of AI has introduced a wave of new terminology, often making it difficult to distinguish between concepts like Agentic AI and Generative AI. This tutorial breaks down these differences in a clear, practical way — and guides you through building your own AI agent from scratch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7QqFnY-W47K6HmqY" /><figcaption>Photo by <a href="https://unsplash.com/@zachmmalin?utm_source=medium&amp;utm_medium=referral">Zach M</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Difference between Generative AI and Agentic AI</h3><p>The fundamental difference lies in the <strong>execution of tasks</strong>. While Generative AI is a reasoning engine we talk to, Agentic AI uses that reasoning engine to perform a series of actions autonomously to reach a specific objective.</p><h3><strong>Generative AI: A brain that can react </strong>(System primarily focused on input and output) and its features/capabilities</h3><p><strong>Next-Word Prediction: </strong>Generative AI is basically a tool that uses vast training context to predict entire answers or code snippets based on a user’s prompt.</p><p><strong>Lack of Action: </strong>Generative AI lacks the ability to execute tasks independently. To get more output, the user must provide more input, making it a purely reactive process.</p><p><strong>Chat-Centric: T</strong>he user simply communicates with the brain to receive information.</p><h3><strong>Agentic AI: Body Parts with a brain </strong>that allows it to take actions and its features/capabilities</h3><p><strong>Planning: </strong>An agent breaks down the high-level goal into individual, achievable steps. This phase is critical for overcoming token limits and ensuring complex tasks are handled systematically.</p><p><strong>Reasoning: </strong>Power derived from the LLM, allowing the agent to think through the planning and execution phases.</p><p><strong>Goal Setting: </strong>The user provides a high-level goal, as the agent cannot find goals on its own.</p><p><strong>Memory: </strong>Use memory (mostly through databases) to keep track of what has been done or to learn from previous tasks, providing better context for future steps.</p><p><strong>Autonomy and Tools: </strong>Granted through tools that allow the agent to interact with the world.</p><h3>Frameworks</h3><ul><li><strong>LangGraph:</strong> The easiest starting point for beginners.</li><li><strong>Other Popular Frameworks:</strong> AutoGPT, CrewAI, and Microsoft’s Autogen etc.</li></ul><p>In the sample project, we will build an agent using <a href="https://www.python.org/downloads/release/python-3144/">Python</a> and the <a href="https://huggingface.co/">Huggingface</a> API to read a text file of tasks and autonomously categorize them into priority buckets ( Mac + VS Code ).</p><p>The complete source code is available at <a href="https://github.com/sreeharikv112/agtdevsample">https://github.com/sreeharikv112/agtdevsample</a></p><p>First and foremost, install Python in your system, and then you shall create a virtual environment ( not mandatory but advisable) and install the required libraries. As I am using a Mac, a few commands may vary in windows machine. I am using Python 3.14.3 in this demonstration and VS Code for development.</p><p>Command to create a virtual environment.</p><pre>python3.11 -m venv agtdemosample</pre><p>Activate the VM using the command below.</p><pre>source agtdemosample/bin/activate<br>source agtdemosample/scripts/activate [ Windows ]</pre><pre>pip install — upgrade pip<br>pip install python-dotenv<br>pip install huggingface_hub<br>pip install transformers accelerate<br>touch .env [ Create file with required changes in Windows]</pre><p>For loading variables from .env file into the environment and keep the Huggingface API key in .env</p><p>Before we start, let us understand the high-level steps involved in this process.</p><ol><li>Reads a list of tasks from a file</li><li>Sends those tasks to an AI model hosted on Hugging Face</li><li>Asks the model to categorize tasks into priorities</li><li>Prints the categorized summary</li></ol><p>Imports required can be cross-checked in the file named task_agent_sample.py <a href="https://github.com/sreeharikv112/agtdevsample">https://github.com/sreeharikv112/agtdevsample</a></p><p>Configuration Section:- Here we will use the constants used across the program.</p><pre>MODEL_NAME = “mistralai/Mistral-7B-Instruct-v0.2”<br>MAX_TOKENS = 300<br>TEMPERATURE = 0.7<br>TASK_FILE_PATH = “tasks.txt”</pre><ul><li>MODEL_NAME → AI model used (from Hugging Face)</li><li>MAX_TOKENS → Maximum length of AI response</li><li>TEMPERATURE → Controls randomness (0 = strict, 1 = creative)</li><li>TASK_FILE_PATH → Input file location</li></ul><pre>load_dotenv()</pre><p>Here we will load environment variables from .env file.</p><pre>HF_API_TOKEN = os.getenv(“HUGGINGFACEKEY”)</pre><p>The API Key stored in the .env will be fetched securely.</p><pre>hf_client = InferenceClient(token=HF_API_TOKEN)</pre><p>Now we will be creating a client to call Hugging Face APIs.</p><pre>def read_task_file(file_path: str) -&gt; Optional[str]:</pre><p>Here we will be reading tasks from a file.</p><pre>with open(file_path, “r”, encoding=”utf-8&quot;) <br>return file.read().strip()</pre><p>We will be reading a file and returning the content.</p><pre>def build_prompt(tasks: str) -&gt; str:</pre><p>This helps to build an effective prompt input for the AI model, which embeds tasks into a structured instruction and also defines the expected output format.</p><h3><strong>Important to understand that AI models behave better when:</strong></h3><ul><li>Instructions are clear</li><li>Output format is enforced in the required format</li></ul><h3>AI Processing Function</h3><pre>def generate_task_summary(tasks: str) -&gt; Optional[str]: <br>prompt = build_prompt(tasks)<br>response = hf_client.chat_completion(<br> model=MODEL_NAME,<br> messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br> max_tokens=MAX_TOKENS,<br> temperature=TEMPERATURE,<br>)<br>response.choices[0].message[&quot;content&quot;]</pre><p>The importance of making a better prompt is explained in the function build_prompt. Here we have embedded the tasks into structured instruction and defined the expected output format for better results. Make sure to use either pre-defined prompts/prompts that provide value addition to your use cases.</p><p>Now moving ahead, chat_completion is the method provided in InterfaceClient through which we can interact with chat-based LLM ( Large Language Models ).</p><h4>LLM model, which we have used in this demonstration, is mistralai/Mistral-7B-Instruct-v0.2 . This is an instruction-tuned LLM that is good for summarization, classification, and providing structured output. And this is suitable for our use case.</h4><p>Why is this important? — Answer is different models behave differently and come with different costs and quality.</p><p>Now the next part is messages=[{“role”: “user”, “content”: prompt}]. This essentially means that we are sending one message from the user containing the task categorization prompt. You can find the Role’s explanation below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*OAamOeHNy5yBS1IV-08t7A.png" /></figure><p>The next part is the token. max_tokens=MAX_TOKENS. This controls the maximum length of the AI response.</p><p>Please note tokens ≠ words and roughly 1 token ≈ 0.75 words</p><p>And why is this required?</p><ul><li>Prevents overly long responses</li><li>Controls cost (in paid APIs)</li></ul><p>Example max_tokens=50 = short summary and max_tokens=500 =detailed output.</p><p>The next part is temperature=TEMPERATURE. This controls the randomness and creativity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*GCWra4H7qThEiuZTJSJHNQ.png" /></figure><p>As the response will be in this format</p><pre>{<br> “choices”: [<br>  {<br>      “message”: {<br>      “role”: “assistant”,<br>       “content”: “High Priority:\n- Task 1\n…”<br>                  }<br>               }<br>            ]<br>          }</pre><p>And we have retrieved the response using this statement response.choices[0].message[“content”]</p><p>This is the main Function (Orchestrator)def main() -&gt; None:</p><p>And this is the entry point</p><p>if __name__ == “__main__”:<br> main()</p><p>In order to run the program, after VM activation and applying the Huggingface API key in .env file , in the terminal execute python task_agent_sample.py. You will get output similar to the screen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xLn8jxKrb1WcC5Zga9rEsg.png" /></figure><p>Here you can see that the tasks which we had mentioned in task.txt are segregated into High/Medium and Low Priority by LLM.</p><p>Hope this read will be helpful to folks who want to try out building agents and get into the world of fascinating AI.</p><p>Cheers and Happy Reading</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fVVgzFci9_26_rl5" /><figcaption>Photo by <a href="https://unsplash.com/@buddhaelemental3d?utm_source=medium&amp;utm_medium=referral">Buddha Elemental 3D</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74f3f31c9125" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customizing AI models and key decision makers in the process]]></title>
            <link>https://sreeharikv112.medium.com/customizing-ai-models-and-key-decision-makers-in-the-process-0030bb1626da?source=rss-500a950c8175------2</link>
            <guid isPermaLink="false">https://medium.com/p/0030bb1626da</guid>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Sreehari Vasudevan]]></dc:creator>
            <pubDate>Wed, 08 Apr 2026 06:37:19 GMT</pubDate>
            <atom:updated>2026-04-08T07:33:19.293Z</atom:updated>
            <content:encoded><![CDATA[<p>Most of us use multiple ways to customize models, but often find it tricky to identify which technique to use and when. This is one of the most critical parts of business, as this impacts the timeline and cost of the AI products. This article explains the AI context and key decision factors that need to be considered during the process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3B0u3wDh6Kh8UvXw" /><figcaption>Photo by <a href="https://unsplash.com/@omilaev?utm_source=medium&amp;utm_medium=referral">Igor Omilaev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article will compare the techniques below and their pros and cons:-</p><ol><li>Prompt Engineering</li><li>RAG</li><li>Fine Tuning</li><li>Pre-Training</li></ol><h3>1. Prompt Engineering</h3><p>In customizing LLMs, Prompt Engineering is the foundation. In this area, we don&#39;t need to modify the model, but enhancing the instructions or context will be targeted. This is fast and cheap compared to other options of LLM customization.</p><p>The effort required is low compared to other options.</p><p><em>Main aspects:-</em></p><p>a) Improve instructions, context, and examples.</p><p>b) Don’t change the model (Underlying neural network doesn’t change. No retraining done, no gradient updates done, and no parameter modification)</p><p>c) Example: — Using GPT-4 or Llma3 as it is.</p><h3>2. RAG (Retrieval-Augmented Generation)</h3><p>In this option, we can connect models to external data sources (Publicly available resources / API’s / Database etc ). The model retrieves the required information and then generates answers. This makes RAG more powerful, as we are not overloading LLMs with pre-trained data, and external information sources help find the required outcome.</p><p><em>Main aspects</em></p><p>a) Maintainable and scalable.</p><p>b) Need not retrain LLM.</p><p>c) Includes domain-specific details using external data sources.</p><p>d) Knowledge lives outside the model.</p><p>e) Hallucinations can be reduced.</p><p><strong><em>RAG Workflow</em></strong>: — User Query —&gt; Embedding Model —&gt; Vector DB (semantic search) → Top N relevant documents → Prompt (context injection) →LLM generates answer</p><p><em>RAG + Prompt engineering (Realtime use cases)</em></p><p>i) As RAG is not standalone, we still need prompt engineering.</p><p>Context: [ retrieved docs]</p><p>Question: [ user query ]</p><p>Instructions: [ Answer only from context, sources ]</p><p>ii) Prompt — Control</p><p>iii) RAG — More knowledge</p><h3>3. Fine Tuning</h3><p>Using the data set available, we need to train the model. This is more about behavior rather than knowledge. Fine-tuning can change response format/tone of response/behavior, etc.</p><p><em>Main aspects</em></p><p>a) High customization.</p><p>b) More about behavior than response itself.</p><p>c) Changes the format/tone etc.</p><p>d) This could be expensive as it requires data as well as multiple retraining cycles.</p><h3>4. Pre-Training</h3><p>This usually deals with training a model from scratch. Using this option, we will have good control, as deep industry knowledge can be fed to LLM while training. But this would need a large contextual data set along with good hardware support.</p><p><em>Main aspects</em></p><p>a) If deep industry knowledge is required as an outcome.</p><p>b) Requires large contextual data and hardware.</p><p>c) Comparatively expensive.</p><h3>5. What option to choose (Decision Aspects)</h3><h4>5.1 Use Prompt Engineering when</h4><p>a) Fast time to market is required.</p><p>b) Low cost to be maintained.</p><p>c) The problem is instruction sensitive and not knowledge heavy.</p><p>d) No pipelines required.</p><p>e) No infra setup required.</p><p>f) Useful for MVPs / early stage features.</p><h4>5.2 Use RAG when</h4><p>a) Knowledge updates are required based on queries.</p><p>b) LLMs are static after training, and this does not suffice for use cases.</p><p>c) Base models don’t know internal data, and we cannot expose data for training.</p><p>d) Reduce hallucinations.</p><p>e) Use cases are document-heavy. ( LLM’s context window is limited)</p><p>f) Need schematic search + reasoning.</p><p>g) To achieve low cost vs. fine-tuning.</p><p>h) Documents / DB’s</p><h4>5.3 Using Fine-Tuning when</h4><p>a) We are having repetitive, high-volume tasks.</p><p>b) Requires a consistent/repeatable output format.</p><p>c) Need behavior/style to be included in response.</p><p>d) Having labeled training data available.</p><p>e) Helps in task specialization ( Financial risk scoring/insurance claim classification, etc )</p><p>f) Less dependency on external data retrieval / lower latency.</p><h4>5.4 Using Pre-training when</h4><p>a) Domain is highly specialized and needs domain intelligence.</p><p>b) Available models do not have industry-specific knowledge.</p><p>c) No external API dependency to be used in the system / No data leak.</p><p>d) Required custom reasoning patterns.</p><p>e) Huge compute / data resources are available.</p><p>f) Fully optimized for the required specific use cases.</p><p>g) Having repetitive, high-volume tasks.</p><p>Hope the above differentiation and details give you a good idea about the choices and when to use which technique.</p><p>Hope you found this story useful and Happy Reading !!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fxU17Opxt3UoAFcL" /><figcaption>Photo by <a href="https://unsplash.com/@hellosmith?utm_source=medium&amp;utm_medium=referral">Rowen Smith</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0030bb1626da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Data JPA -One To Many and Join Query]]></title>
            <link>https://sreeharikv112.medium.com/spring-data-jpa-one-to-many-and-join-query-a6bc329d93dd?source=rss-500a950c8175------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6bc329d93dd</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[spring-data-jpa]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[one-to-many-relationship]]></category>
            <dc:creator><![CDATA[Sreehari Vasudevan]]></dc:creator>
            <pubDate>Thu, 28 Aug 2025 14:07:32 GMT</pubDate>
            <atom:updated>2026-04-24T11:29:45.185Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RL9wl8SdNSnIZRGr" /><figcaption>Photo by <a href="https://unsplash.com/@pawel_czerwinski?utm_source=medium&amp;utm_medium=referral">Pawel Czerwinski</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In many projects, entity relationship mapping and join operations in Spring Data JPA can feel challenging at first. This tutorial provides straightforward examples to make these concepts easier to understand and apply in practice.</p><p>Create a Spring Boot project using spring initializer (<a href="https://start.spring.io/">https://start.spring.io/</a>) and import it into the project if you are using Eclipse. Or you can go with IntelliJ. In this example, I am using IntelliJ IDE. Select the options below and enter details below as per your context. Name, Language, Type (select Maven), Group ID, Artifact ID, package name, required JDK, and packaging. Click next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*LcgZGHH3nyJ7IU3NuTehyw.png" /></figure><p>Now we need to add the required dependencies. Spring Web, Lombok, Spring Data JPA, MySQL Driver.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9KTGS6_lWJBbxr8M7SWavg.png" /></figure><p>Click Create in IntelliJ. If you are using spring initializer (<a href="https://start.spring.io/">https://start.spring.io/</a>), the Zip file can be downloaded. You can extract and open the same in IDE. Create these folders in the project.</p><ol><li>controller ( REST controllers will be included here)</li><li>dto ( Objects that should not contain any business logic or methods implementation ie, holds properties and has getters and setters)</li><li>entity (Database entities classes will be added here)</li><li>repository (Class responsible for interacting with DB of your choice)</li><li>services (business logic ie, rules, calculations, orchestration etc will be included in this layer)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*TmjXmzxadh0lCCY0kGMyVw.png" /></figure><p>5. Now open the application.properties under the resources folder and mention the database details and schema name (Example:- custprodonetomany). In this example, I am using MySQL DB.</p><pre>spring.datasource.url=jdbc:mysql://localhost:3306/dbschemaname<br>spring.datasource.username=username<br>spring.datasource.password=password<br>server.port=8080<br>server.servlet.context-path=/customer-service<br>spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver<br>spring.jpa.hibernate.ddl-auto=update</pre><p>You can find the complete source code on my GitHub.</p><p><a href="https://github.com/sreeharikv112/SpringJPAOneToMany">https://github.com/sreeharikv112/SpringJPAOneToMany</a></p><p>To explain the scenario, we will consider two aspects of business workflow.</p><ol><li>Customer attributes and aspects</li><li>How customer is related to the Product details</li></ol><p>Now to explain one to may, one customer can buy more than one product from a shopping portal. So we will consider our example as one customer entity can have more than one product, ie, a list of products which he/she can purchase. Below parameters we will consider in the customer entity. The Customer class will be the JPA entity that represents a customer record in the database.</p><pre>@Data<br>@NoArgsConstructor<br>@AllArgsConstructor<br>@ToString<br>@Entity<br>public class Customer {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private int id;<br>    private String name;<br>    private String email;<br>    private String gender;<br>}</pre><p>As we already included Lombok, we can avoid Bipolorate code. Rather than explicitly setting getters/setters and constructors, we can use annotations. We will also annotate the class with @Entity to indicate to Hibernate that this class is mapped to a table. Now @GeneratedValue is used in the id attribute to auto-generate the ID value using its identity column mechanism, and each new row inserted will get a unique ID automatically. Similarly Product class will be the JPA entity that represents a product record in the database.</p><pre>@Data<br>@NoArgsConstructor<br>@AllArgsConstructor<br>@ToString<br>@Entity<br>public class Product {<br><br>    @Id<br>    private int id;<br>    private String productName;<br>    private int qty;<br>    private int price;<br>}</pre><p>Now, for having a relationship with the customer and product, below changes we will have in the Customer entity. Here we will be using the Hibernate OneToMany annotation.</p><pre>public class Customer {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private int id;<br>    private String name;<br>    private String email;<br>    private String gender;<br><br>    @OneToMany(targetEntity = Product.class, cascade = CascadeType.ALL)<br>    @JoinColumn(name=&quot;cp_fk&quot;, referencedColumnName = &quot;id&quot;)<br>    private List&lt;Product&gt; products;<br>}</pre><p>Let us now break it down with further details. As a customer can have more than one product, we are specifying the target entity as the Product class. Cascade type ALL means, any operation done on the customer will also be applied to the products. This could be:-</p><p>PERSIST → Saving a customer saves all products.</p><p>REMOVE → Deleting a customer deletes its products.</p><p>MERGE, REFRESH… etc</p><p>Now coming to further statements, ie:-</p><pre>@JoinColumn(name=&quot;cp_fk&quot;, referencedColumnName = &quot;id&quot;)</pre><p>This is a unidirectional relationship. The product does not have a customer field. But the product table will have a foreign key column named <strong>cp_fk</strong>. <strong>cp_fk</strong> will be the column in the product table that stores the customer’s id. referencedColumnName = “<strong>id</strong>” this foreign key refers to the id column in the customer table.</p><p>During the runtime, when we save the customer with list of products, hibernate inserts the customer row first. Then inserts each product row with <strong>cp_fk</strong> to set that customer’s id.</p><p>Moving further, we will create two repositories in the repository package. These will be interfaces and will extend JpaRepository with the respective target entity and data type of the primary key. So the first one will be CustomerRepository.</p><pre>public interface CustomerRepository extends JpaRepository&lt;Customer,Integer&gt; {<br>}</pre><p>The next one will be ProductRepository</p><pre>public interface ProductRepository extends JpaRepository&lt;Product,Integer&gt; {<br>}</pre><p>We will use a DTO class to transfer the data. For this, we will create an order request class like below.</p><pre>@AllArgsConstructor<br>@NoArgsConstructor<br>@ToString<br>@Data<br>public class OrderRequest {<br><br>   private Customer customer;<br>}</pre><blockquote>Although the tutorial is less complicated, it is good to maintain service layer; where the business logic is handled in service layer and controller only does Request handling , Input validation, Converting HTTP data (JSON/XML) into domain objects, Returning responses etc.</blockquote><blockquote>Technically we can include logic in controller, but it will create problems with respect to reusability, testability, separation of concerns, maintainability etc.</blockquote><p>So we will create a service layer and create a new class named OrderServices in the services package and include below statements. Through CustomerRepository, we will be able to do require operations, so that the Controller can call corresponding methods and just get back with success/error responses.</p><pre><br>@Service<br>@RequiredArgsConstructor<br>@Slf4j<br>public class OrderServices {<br><br>    private final CustomerRepository customerRepository;<br><br>    public Customer placeOrderLogic(OrderRequest request){<br>        log.info(&quot;Order Placed Successfully&quot;);<br>        return customerRepository.save(request.getCustomer());<br>    }<br>    public List&lt;Customer&gt; findAllOrderDetails(){<br>        log.info(&quot;Fetching all Order Details&quot;);<br>        return customerRepository.findAll();<br>    }<br>    public List&lt;OrderResponse&gt; getCustomerAndProducts(){<br>        log.info(&quot;Combine customer and product details&quot;);<br>        return customerRepository.getJoinInfo();<br>    }<br>}</pre><p>Now we can proceed with the Controller class creation. We can create one endpoint for placing an order with products, as well as another one for finding all orders.</p><p>Annotate the class with @RestController. Use @RequiredArgsConstructor to inject services, use @PostMapping for post request (placing an order), and @GetMapping for fetching all records (getting all orders).</p><pre><br>@RestController<br>@RequestMapping(&quot;/api&quot;)<br>@RequiredArgsConstructor<br><br>public class OrderController {<br><br>    private final OrderServices orderServices;<br><br>    @PostMapping(&quot;/placeOrder&quot;)<br>    @ResponseStatus(HttpStatus.CREATED)<br>    public Customer placeOrder(@RequestBody OrderRequest request){<br>        return orderServices.placeOrderLogic(request);<br>    }<br><br>    @GetMapping(&quot;/findAllOrders&quot;)<br>    @ResponseStatus(HttpStatus.OK)<br>    public List&lt;Customer&gt; findAllOrder(){<br>        return orderServices.findAllOrderDetails();<br>    }<br><br>    @GetMapping(&quot;/getCustomerAndProductInfo&quot;)<br>    @ResponseStatus(HttpStatus.OK)<br>    public List&lt;OrderResponse&gt; getCombinedCustomerAndProductInfo(){<br>        return orderServices.getCustomerAndProducts();<br>    }<br>}</pre><p>Before we run the application, just make sure we have the MySQL instance open with the required setup. Once you run the application and if everything goes well without errors, you can see logs below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NTCbGrSEk9_PMbHrgW-R4g.png" /><figcaption>Tomcat started on port 8080 (http) with context path ‘/customer-service’.</figcaption></figure><p>This means the application does not have any errors, and the server is running on port 8080. Note:- If you find this failing, check if any other apps are running using this port; if then you can change the port number from application.properties file. Re-run the Spring Boot application. If the application is running successfully, both the customer and product tables will get created in DB.</p><p>Now we can create and save customer record with the required product details, which should get saved into the product table using the join column that we mentioned in the Customer entity.</p><p>Open a REST client of your choice ( Postman / Hoppscoth etc) and try to hit URL below with the required request body.</p><p><a href="http://localhost:8080/customer-service/placeOrder">http://localhost:8080/customer-service/api/placeOrder</a></p><p>This will be a POST request. Open the request body. Select content type as raw- application/json and paste below sample request body.</p><pre>{<br>  &quot;customer&quot;: {<br>    &quot;name&quot;: &quot;Algin&quot;,<br>    &quot;email&quot;: &quot;Algin@gmail.com&quot;,<br>    &quot;gender&quot;: &quot;male&quot;,<br>    &quot;products&quot;: [<br>      {<br>        &quot;pid&quot;: 1,<br>        &quot;productName&quot;: &quot;Laptop&quot;,<br>        &quot;qty&quot;: 1,<br>        &quot;price&quot;: 2000<br>      },<br>      {<br>        &quot;pid&quot;: 2,<br>        &quot;productName&quot;: &quot;Mobile&quot;,<br>        &quot;qty&quot;: 1,<br>        &quot;price&quot;: 250<br>      }<br>    ]<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*veHDwE4YlL23ckkv0qszXw.png" /></figure><p>Create one more record with different customer details and product details like below, so that we can validate the foreign key details mapped to the customer in DB.</p><pre>{<br>  &quot;customer&quot;: {<br>    &quot;name&quot;: &quot;Rimple&quot;,<br>    &quot;email&quot;: &quot;Rimple@gmail.com&quot;,<br>    &quot;gender&quot;: &quot;female&quot;,<br>    &quot;products&quot;: [<br>      {<br>        &quot;pid&quot;: 3,<br>        &quot;productName&quot;: &quot;Car&quot;,<br>        &quot;qty&quot;: 1,<br>        &quot;price&quot;: 30000<br>      },<br>      {<br>        &quot;pid&quot;: 4,<br>        &quot;productName&quot;: &quot;Bag&quot;,<br>        &quot;qty&quot;: 1,<br>        &quot;price&quot;: 670<br>      }<br>    ]<br>  }<br>}</pre><p>After hitting this endpoint, check in DB tables, you can see updates below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NZZ0vpQfcokjitquiEIl3A.png" /></figure><p>Here you can see that two customer records got created in the customer table. Four products got created in the product table. And the <strong>cp_fk</strong> column representing the foreign key is also having a corresponding customer ID mapped.</p><p>To validate the same using API, we can hit the second endpoint like below and use GET rather than POST this time.</p><p><a href="http://localhost:8080/customer-service/findAllOrders">http://localhost:8080/customer-service/</a><a href="http://localhost:8080/customer-service/placeOrder">api/</a><a href="http://localhost:8080/customer-service/findAllOrders">findAllOrders</a></p><p>This query will pull customer details along with related product details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lC3H5Ws7PGgn_2Sm3jz2Yg.png" /></figure><p>For representing the Join operation, we will fetch the name, email from the customer table. Also, we will fetch the product name and quantity from the product table. To do this, we will get back to our CustomerRepository and, using the <strong>Projection Interface </strong>pattern,<strong> </strong>create an interface like below.</p><pre>public interface OrderResponse {<br>    String getName();<br>    String getEmail();<br>    String getProductName();<br>    Integer getQuantity();<br>}</pre><p>Instead of returning full Customer or Product entities, we can <strong>map query results directly</strong> into this interface.</p><p>Spring will automatically match with SQL/JPA alias:-</p><ul><li>getName() → name</li><li>getEmail() → alias email</li><li>getProductName() → alias productName</li><li>getQuantity() → alias quantity</li></ul><p>Now our query also needs to return results with exactly these aliases</p><pre>@Repository<br>public interface CustomerRepository extends JpaRepository&lt;Customer,Integer&gt; {<br>    @Query( &quot;SELECT c.name AS name, c.email AS email, p.productName AS productName, p.qty AS quantity FROM Customer c JOIN c.products p&quot;)<br>    List&lt;OrderResponse&gt; getJoinInfo();<br>}</pre><p>Here @Query defines a custom JPQL (not raw SQL)</p><ul><li>It <strong>joins</strong> Customer (c) with their associated products (p).</li><li>It <strong>selects specific fields</strong> instead of full entities.</li><li>The AS name, AS email, AS productName, AS quantity ensures those maps correctly into OrderResponse.</li></ul><h3>Why use this approach?</h3><p>✅ Better <strong>Performance</strong> → Only required fields are fetched (not full entities).<br>✅ <strong>Readability</strong> → We can avoid writing DTO classes manually.<br>✅ <strong>Clean Mapping</strong> → Projection interfaces auto-map from query aliases.</p><p>Common issues that could cause and need to be kept in mind are (nullresponse ):-</p><ul><li>The entity field name doesn’t match (p.qty must be exactly the field in the Product entity).</li><li>Or the alias doesn’t match the projection method (AS quantity must match getQuantity()).</li></ul><p>Now, for running this operation, we need to add another endpoint in the controller class ( GET request).</p><pre>@GetMapping(&quot;/getCustomerAndProductInfo&quot;)<br>@ResponseStatus(HttpStatus.OK)<br>    public List&lt;OrderResponse&gt; getCombinedCustomerAndProductInfo(){<br>        return customerRepository.getCustomerAndProducts();<br>    }</pre><p>After running the below endpoint, we will be able to see the combined response from the two tables.</p><p>http://localhost:8080/customer-service/api/getCustomerAndProductInfo</p><p>API Response:-</p><pre>[<br>  {<br>    &quot;name&quot;: &quot;Algin&quot;,<br>    &quot;email&quot;: &quot;Algin@gmail.com&quot;,<br>    &quot;productName&quot;: &quot;Laptop&quot;,<br>    &quot;quantity&quot;: 1<br>  },<br>  {<br>    &quot;name&quot;: &quot;Algin&quot;,<br>    &quot;email&quot;: &quot;Algin@gmail.com&quot;,<br>    &quot;productName&quot;: &quot;Mobile&quot;,<br>    &quot;quantity&quot;: 1<br>  },<br>  {<br>    &quot;name&quot;: &quot;Rimple&quot;,<br>    &quot;email&quot;: &quot;Rimple@gmail.com&quot;,<br>    &quot;productName&quot;: &quot;Car&quot;,<br>    &quot;quantity&quot;: 1<br>  },<br>  {<br>    &quot;name&quot;: &quot;Rimple&quot;,<br>    &quot;email&quot;: &quot;Rimple@gmail.com&quot;,<br>    &quot;productName&quot;: &quot;Bag&quot;,<br>    &quot;quantity&quot;: 1<br>  }<br>]</pre><p>With these details, this tutorial, which explains the One To Many Relationship in Spring Boot is concluded with a simple example. Hope all readers who wanted to have step-by-step explanation for this context will find this helpful.</p><p>You can find the complete source code on my GitHub.</p><p><a href="https://github.com/sreeharikv112/SpringJPAOneToMany">https://github.com/sreeharikv112/SpringJPAOneToMany</a></p><p>Thanks for reading✌️ Happy Coding 👨‍💻 Cheers 🥂🍻</p><p><strong>Edit</strong>:- <em>Added sample unit test cases to evaluate OrderController’s placeOrder method. The same can be found in test package. As the tutorial will become lengthy, just keeping a note here for reference.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6bc329d93dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Product evolution steps and strategies (product lifecycle evolution)]]></title>
            <link>https://sreeharikv112.medium.com/product-eveolvement-steps-and-strategies-product-lifecycle-evolution-8c9db9165726?source=rss-500a950c8175------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c9db9165726</guid>
            <category><![CDATA[strategy]]></category>
            <category><![CDATA[digital-marketing]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[saas-marketing]]></category>
            <dc:creator><![CDATA[Sreehari Vasudevan]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 18:14:10 GMT</pubDate>
            <atom:updated>2025-08-01T18:20:45.252Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cFUeS4C1E5e3lk8h" /><figcaption>Photo by <a href="https://unsplash.com/@epicantus?utm_source=medium&amp;utm_medium=referral">Daria Nepriakhina 🇺🇦</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It’s been a while since I last shared content aimed at adding value to readers. Today, I’d like to explore practical ideas that can be effectively applied throughout the product lifecycle journey.</p><p>A tailored version of the product evolvement steps and strategies, focusing on software, SaaS, and digital products in tech industry are described below. All these 6 pointers are major milestones that are important for any product to be successful.</p><h3>1. Ideation and Market Discovery</h3><p>In the tech industry, product development starts with a strong ideation phase that leverages insights from data, emerging technologies, and evolving user behavior. Teams identify pain points through user research, analyze gaps in current solutions, and explore disruptive opportunities using tools like SWOT analysis and design thinking. Special attention is given to technology trends (e.g., AI, edge computing etc) that can be leveraged to offer unique value propositions. This phase is crucial for identifying product-market fit potential before resource investment.</p><h3>2. Concept Validation and MVP Strategy</h3><p>With a validated problem statement, the next step is to shape the solution into a working prototype or MVP (Minimum Viable Product). In tech, this often means building a lean, core-functionality product with rapid prototyping tools, mock APIs, or no-code/low-code platforms. The strategy is to deploy fast, test real users early, and iterate based on usage metrics. Customer interviews, clickstream data, and early adopter programs help refine the direction before scaling. Tech companies often use this phase to secure seed funding or internal buy-in.</p><h3>3.Agile Development and Scalable Architecture</h3><p>Once the MVP gains traction, the development process shifts into high gear using agile or DevOps methodologies. Sprints, stand-ups, and backlog grooming help maintain velocity and focus. Scalability becomes a priority — whether through cloud-native architecture, microservices, containerization, or serverless deployments. Continuous Integration and Continuous Deployment (CI/CD) pipelines ensure rapid iteration without sacrificing quality. UX/UI design remains central, with tools like Figma, Jira, and GitHub facilitating seamless collaboration across product, engineering, and design teams.</p><h3>4. Product Launch and GTM Execution</h3><p>In tech, launching a product is both technical and strategic. Beyond making the app or platform publicly available, companies craft go-to-market (GTM) strategies that include growth marketing, channel partnerships, onboarding automation, and performance analytics. Beta testing or phased rollouts (via feature flags or regional deployments) are used to monitor load, gather user feedback, and avoid downtime. SEO, product-led growth (PLG), community building, and developer evangelism play key roles in scaling adoption quickly and organically.</p><h3>5. Growth, Data Analytics, and Continuous Improvement</h3><p>After launch, successful tech products invest heavily in growth loops and feedback systems. Teams monitor KPIs such as DAUs/MAUs, churn rate, retention cohorts, and Net Promoter Score (NPS). Product analytics platforms (like Mixpanel, Amplitude, or GA4) are used to understand user behavior and inform A/B testing or feature prioritization. Advanced strategies may include personalization algorithms, predictive analytics, and AI-powered recommendations to boost engagement. Cross-functional alignment between product, engineering, sales, and customer success is critical to drive continued evolution.</p><h3>6. Product Maturity, Innovation, and Lifecycle Evolution</h3><p>As the product matures, tech companies explore ways to extend the lifecycle — through new features, integrations, modular platforms, or market expansion. They may develop an ecosystem (e.g., APIs, SDKs, plug-ins) to support community innovation. Simultaneously, tech debt and legacy code are addressed via refactoring or architectural upgrades. Forward-looking teams invest in R&amp;D, tech scouting, and pilot programs to identify the “next big thing,” ensuring continued innovation and avoiding stagnation. At this stage, lifecycle planning includes user migration strategies and sunset plans for deprecated features.</p><p>By embedding user feedback and behavioral data into every phase — from ideation to maturity — companies can build solutions that truly resonate and scale with confidence.</p><p><em>Always remember that every successful tech product evolution begins and ends with the user. Great tech products aren’t born perfect — they’re shaped by a deep understanding of user needs, relentless iteration, and bold vision. Success lies in evolving, not just launching.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c9db9165726" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Platform Widgets and Usage]]></title>
            <link>https://sreeharikv112.medium.com/flutter-platform-widgets-and-usage-5bbf335eeaec?source=rss-500a950c8175------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bbf335eeaec</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <dc:creator><![CDATA[Sreehari Vasudevan]]></dc:creator>
            <pubDate>Sun, 24 May 2020 05:06:20 GMT</pubDate>
            <atom:updated>2020-05-31T08:00:28.053Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p0DOa0o5aPA_1psyIHbR0Q.png" /></figure><p>While going through cross platform solutions, it is expected one code base to give platform specific behaviour while deployed into individual platforms. Eventhough google is more aligned to push Material Design for all platforms, it would be unfair to force the same on <a href="https://en.wikipedia.org/wiki/Steve_Jobs">Great Steve Jobs</a> 💖 fans ✌️, who’s family already suggested <a href="https://developer.apple.com/design/human-interface-guidelines/ios/overview/themes/">Human Interface Guidlines</a> for ios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HOGG7AXcwrlL9tAs" /><figcaption>Big Salute to the Legend</figcaption></figure><p>Luckily there is <a href="https://flutter.dev/docs/development/ui/widgets/cupertino">platform widget’s library</a> developed by google itself , which is having support for many widgets (not all for now 😟) and lets hope for more in future. This article is speculating usage of platform specific widgets in Flutter and its implications.</p><p>Main flutter setup does not change much. As Cupertinos and platform widgets need to be included, we require the below dependency in pubspec.yaml file. Run get packages and dependencies will be added to your project.</p><pre>cupertino_icons: ^0.1.3<br>flutter_platform_widgets: ^0.50.0</pre><p>Now, in-order to start with, let’s tell source to handle different <em>patterns</em> for both the platforms. By naming <em>pattern</em>, lets give it a global meaning which has different aspects in different platforms to achieve the same outcome. In Android, screens may or may not have back navigation button in app bar due to presence to physical back button (This physical button’s may change in future with Gesture naviation for utilizing the screen real estate😇). But for iOS we need mandatory back button in left side of the app bar as there is no physical back button. In iOS , title will be placed in centre of the app bar, were as in Android title will be aligned to left side in app bar. Like wise the differences go on increasing in different scenarios.</p><p>Open the main.dart file. By default flutter apps will have StatelessWidget. This widget’s build method will return MaterialApp like below.</p><pre>@override<br>Widget build(BuildContext context) {<br>return MaterialApp(<br>title: &#39;Flutter Demo&#39;</pre><p>For having platform specific app, we will remove this <em>MaterialApp</em> and replace it with <em>PlatformApp</em> from and pass specific theme for two platforms. (flutter_platform_widgets/flutter_platform_widgets.dart)</p><pre>@override<br>Widget build(BuildContext context) {<br>return PlatformApp(<br>title: &#39;Flutter Demo&#39;,<br>android: (_) =&gt; MaterialAppData(theme: materialThemeData),<br>ios: (_) =&gt; CupertinoAppData(theme: cupertinoTheme),</pre><p>You have noticed , I have used different themes in both platform versions. This we can define according to our specification shown as below for materialThemeData.</p><pre>final materialThemeData = ThemeData(<br>primarySwatch: Colors.blue,<br>scaffoldBackgroundColor: Colors.white,<br>accentColor: Colors.blue,<br>appBarTheme: AppBarTheme(color: Colors.blue.shade600),<br>primaryColor: Colors.blue,<br>secondaryHeaderColor: Colors.blue,<br>canvasColor: Colors.blue,<br>backgroundColor: Colors.red,<br>textTheme: TextTheme().copyWith(bodyText1: TextTheme().bodyText2));</pre><p>Now for cupertinoTheme , we can define the following.</p><pre>final cupertinoTheme = CupertinoThemeData(<br>primaryColor: Colors.blue,<br>barBackgroundColor: Colors.blue,<br>scaffoldBackgroundColor: Colors.white);</pre><p>Now define the home screen , I have created AppHomePage under <em>ui</em> folder. And created a stateful widget.</p><pre>class AppHomePage extends StatefulWidget {<br>AppHomePage({Key key, this.title}) : super(key: key);<br>final String title;<br>@override<br>_AppHomePageState createState() =&gt; _AppHomePageState();<br>}</pre><p>Now the _AppHomePageState will be returning PlatformScaffold which will have an appBar, inturn creates PlatformAppBar inside which iOS specific CupertinoNavigationBarData will be defined.</p><p>PlatformScaffold will have another parameter android, which will return MaterialScaffoldData like shown below.</p><pre>class _AppHomePageState extends State&lt;AppHomePage&gt; {<br>@override<br>Widget build(BuildContext context) {<br>return PlatformScaffold(<br>appBar: PlatformAppBar(<br>title: Text(widget.title, style: toolbarTextStyle,),</pre><pre>ios: (_)=&gt; CupertinoNavigationBarData(<br>transitionBetweenRoutes: false,<br>),),</pre><pre>android: (_) =&gt; MaterialScaffoldData(),<br>body: Center(child:Text(&quot;Screen 1&quot;,<br>style: TextStyle(color: Colors.black, fontSize: 30),),));}}</pre><p>Now you can run on both devices. Below will be the outcome👏😇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ziwTohy9o72cawdhSx9xBQ.png" /><figcaption>First impression of platform specific widgets</figcaption></figure><p>As you can see same code base behaves specific to platform with the differentiations we did. Check the differences in title alignment. The source can be found in branch <a href="https://github.com/sreeharikv112/FlutterPlatformSpecificApp">#01-initial-screen</a> over here <a href="https://github.com/sreeharikv112/FlutterPlatformSpecificApp">Github Repo</a>.</p><p>Moving on further, let us add few widgets in screen and see how to handle the same in both platforms. For this task, let us have a Stateful widget as First Screen. And add two entry fields , a switch for remember me and button to mimic look and feel of a login screen. And an icon at the top as well.</p><p>For icons, we can use Icon(context.platformIcons. …) , but which has a limited number of assets available. Let’s have a nice logo at the top before the entry fields. I ‘m a big fan of <strong>Avengers</strong>. Hence got an <strong>Iron Man</strong> face logo from <a href="https://icons8.com/icons">https://icons8.com/icons</a></p><p>For adding platform icon or regular icon, the pattern is same. But here we will be referring to the downloaded icon which will be kept in images folder of our project. In-order to add the icon , we should edit the pubspec.yaml file. There should be a 2 space difference between the parent in pubspec file.</p><pre>assets:<br>  - images/icon_iron_man.png</pre><p>Now we can refer the icon in our screens. For doing so, within our _FirstScreenState , create a method , which will return Widget , who’s container will be having an Image as child.</p><pre>Widget getAssetImage() {</pre><pre>AssetImage assetImage = AssetImage(&#39;images/icon_iron_man.png&#39;);<br>Image image = Image(image: assetImage,width: 125.0,height: 125.0,);</pre><pre>return Container(<br>padding: EdgeInsets.only(top: padding_20, bottom: padding_20 * 2),<br>child: image,<br>alignment: Alignment.center,);<br>}</pre><p>Now, in the _FirstScreenState, we can refer the same in our column.</p><pre>Widget build(BuildContext context) {</pre><pre>return Column(children: &lt;Widget&gt;[<br>getAssetImage(),<br>//other elements goes here</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ib8ArzawFL-3NPHsezSlwQ.png" /><figcaption>After adding image from asset.</figcaption></figure><p>Now by adding the first screen with 2 entry fields , we will have a user name field and password field (password will be masked) as shown below.</p><pre>class _FirstScreenState extends State&lt;FirstScreen&gt;{</pre><pre>@override</pre><pre>Widget build(BuildContext context) {</pre><pre>return Column(children: &lt;Widget&gt;[</pre><pre>getAssetImage(),</pre><pre>Padding(<br>padding: const EdgeInsets.only(top: 50.0, left: 20.0, right: 20.0),<br>child: PlatformTextField(<br>keyboardType: TextInputType.text,<br>android: (_) =&gt; MaterialTextFieldData(<br>decoration: InputDecoration(labelText: &#39;User name&#39;),),<br>ios: (_) =&gt; CupertinoTextFieldData(<br>placeholder: &#39;User name&#39;,<br>),),),</pre><pre>Padding(<br>padding: const EdgeInsets.all(20.0),<br>child: PlatformTextField(<br>keyboardType: TextInputType.text,<br>android: (_) =&gt; MaterialTextFieldData(<br>decoration: InputDecoration(labelText: &#39;Password&#39;),obscureText: true,),<br>ios: (_) =&gt; CupertinoTextFieldData(<br>placeholder: &#39;Password&#39;,<br>obscureText: true,<br>),),),</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8MzCSVtIHoOuV7aOVVVVfw.png" /><figcaption>Entry fields difference while deployed to both platforms</figcaption></figure><p>Now you can see, there is a considerable difference in the elements when deployed to respective platforms. <strong>These are the main advantages of Platform specific widgets. The adaption when same source is deployed into different platforms is much appreciable</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*Lhkp6ZuBpJQKdiUlmn6-GA.png" /></figure><p>There may be errors like bottom overflowed in some devices. 🤯 Do not panic. Let’s resolve this error later after completing rest of elements in first screen.🤗</p><p>Moving forward, we can have Switch for remember me functionality and login button.</p><pre>Column(<br>mainAxisAlignment: MainAxisAlignment.center,<br>children: &lt;Widget&gt;[</pre><pre>Padding(<br>padding: const EdgeInsets.all(padding_20),<br>child: PlatformSwitch(<br>value: _currentSwitchValue,</pre><pre>onChanged: (value) {<br>setState(() {<br>  _currentSwitchValue = value;<br>if (value) {<br>  switchText = &quot;Yes,&quot;;<br>} else {<br>  switchText = &quot;No, Don&#39;t&quot;;}});<br>},),),</pre><pre>Text(&#39;$switchText remember me &#39;,<br>style: TextStyle(color: Colors.blueGrey, fontSize: 15),),],),</pre><pre>Padding(<br>padding: const EdgeInsets.all(padding_20),<br>child: PlatformButton(<br>onPressed: () {},<br>child: Text(&#39;Login&#39;),<br>android: (_) =&gt; MaterialRaisedButtonData(),<br>ios: (_) =&gt; CupertinoButtonData(),<br>)),</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p0DOa0o5aPA_1psyIHbR0Q.png" /><figcaption>Required elements in login screen</figcaption></figure><p>I have changed the theme, to suite our Iron Man logo. Now you can see, the differences of switches in both platforms. Check and uncheck the Switch, you can see the <em>remember me label changes</em>. Also checkout the button difference. Even though this looks pale, still the platform difference is evident. Let us now handle the error (<em>bottom overflow by XX pixels</em>) as well as , add some validation.</p><p>Inorder to handle overflow error, We have to change the heirarchy. _FirstScreenState will return a ListView 🧐. And inside the listview , we will have an array of widgets. So below are the changes to be applied</p><pre>return ListView(<br>     children: &lt;Widget&gt;[<br>       ....</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fsqAc5Rf9g07dik6de4ESA.png" /><figcaption>The change in hierarchy, will allow us to scroll and avoid the overflow error</figcaption></figure><p>For validation, we will do track of PlatformTextField’s onChanged method. At present the <strong><em>Form’s</em></strong> are not applicable for platform widgets. So we have to do the validation manually or build our own. Let us show an alert (PlatformAlertDialog) if any of the TextFields are empty. For now I am checking only for empty values, you may add any kind of validations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GBBtYYDieeQ4DjkqS7KmUQ.png" /><figcaption>Platform specific alert dialogues</figcaption></figure><p>As this may seems <strong>annoying</strong>, you can avoid this validation from onChanged and only add checking for error scenarios in Login Button. <em>I have kept both for demonstration.</em></p><pre>child: PlatformButton(<br>onPressed: () {</pre><pre>setState(() {<br> if(_userNameEntered.isEmpty || _passwordEntered.isEmpty){<br>   showAlert(&#39;Please enter both user name and password&#39;);<br> }else{<br>   debugPrint(&#39;proceed&#39;);<br> }<br>});},<br>child: Text(&#39;Login&#39;),<br>android: (_) =&gt; MaterialRaisedButtonData(),<br>ios: (_) =&gt; CupertinoButtonData(),)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k8NaPTw-aqoHyD7k5DjJjw.png" /><figcaption>Alert dialog for fields validation.</figcaption></figure><p>The source can be found in branch <a href="https://github.com/sreeharikv112/FlutterPlatformSpecificApp/tree/%2302-elements-in-landing">#02-elements-in-landing</a></p><p>Now lets move on and see , how to navigate from first to second screen post successful login. Create dashboard.dart under same package. Place a text in the body of DashboardScreenState. Create a function named moveToNextScreen and give the below for navigation.</p><pre>void moveToNextScreen(BuildContext context) {<br>  Navigator.pushReplacement(context,MaterialPageRoute(builder:  (context) =&gt; DashboardScreen()),);<br>}</pre><p>If we use regular push, that will cause creation of back button in app bar of Android devices. Now give user name, password and press Login button. You can see the dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vm103QinVXOj_36HoPqqHA.png" /></figure><p>The source can be found in branch <a href="https://github.com/sreeharikv112/FlutterPlatformSpecificApp/tree/%2303-dashboard-added">#03-dashboard-added</a></p><p>In dashboards, there will be quite a good segregation mostly we need to do. So let us create navigation with bottom bar for the same. To start with bottom tabs (three), create three different widgets for three tabs.</p><pre>class ScreenTabOne extends StatelessWidget {</pre><pre>@override<br>Widget build(BuildContext context) {</pre><pre>return Center(<br>child:  Text(<br>&quot;Dashboard&quot;,<br>style: TextStyle(color: Colors.brown, fontSize: 30),<br>),);}</pre><pre>}</pre><p>Similarly create other two. Check screen_tab_one.dart ,screen_tab_two.dart and screen_tab_three.dart. In the DashboardScreenState , give corresponding parameters for bottomNavBar. Which will be the PlatformNavBar. Define the BottomNavigationBarItem with icon, title and active icon for all the three tabs.</p><pre>bottomNavBar: PlatformNavBar(<br>currentIndex: _tabSelectedIndex,<br>itemChanged: (index) {</pre><pre>setState(() {<br>_tabSelectedIndex = index;<br>title = getScreenTitle(index);<br>});},<br>backgroundColor: Colors.blueGrey,</pre><pre>items: [</pre><pre>BottomNavigationBarItem(<br>icon:  Icon(Icons.apps, color: Colors.grey),<br>title:  Text(&#39;Dashboard&#39;, style: ColorUtils.bottomNavTextStyle),<br>activeIcon:  Icon(Icons.apps, color: Colors.white),),</pre><pre>BottomNavigationBarItem(<br>icon:  Icon(Icons.update, color: Colors.grey),<br>title:  Text(&#39;Feeds&#39;, style: ColorUtils.bottomNavTextStyle),<br>activeIcon:  Icon(Icons.update, color: Colors.white),),</pre><pre>BottomNavigationBarItem(icon: Icon(Icons.settings, color: Colors.grey),title: Text(&#39;Settings&#39;,style: ColorUtils.bottomNavTextStyle,),<br>activeIcon:  Icon(Icons.settings, color: Colors.white),)<br>]),</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QJYlMzThJuSZqXdF9qgO2A.png" /><figcaption>After adding bottom nav bar</figcaption></figure><p>With this our initial app flow is completed which exposes the power of Flutter Platform Widgets. By navigating to other tabs the <strong><em>title also will change</em></strong> <strong><em>correspondingly</em></strong>. You can run the app from start and see the complete app flow.</p><p>Full source code can be found over <a href="https://github.com/sreeharikv112/FlutterPlatformSpecificApp">Github</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m23bU8K1pJc3cu3xgTPj5Q.jpeg" /><figcaption>Final version of the screens in both platforms</figcaption></figure><p>If you find this article helpful, do clap 👏👏 which will keep writers motivated to contribute more in the different technological aspects. 😇</p><p>Full source code can be found over <a href="https://github.com/sreeharikv112/FlutterPlatformSpecificApp">Github</a></p><p>Thanks for reading✌️ Happy Coding 👨‍💻 Cheers 🥂🍻</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*wT6-y063jChA3bD4ZM9Siw.gif" /></figure><p>Icons downloaded from <a href="https://icons8.com/icons">https://icons8.com/icons</a></p><p><em>Gif images copyright </em><a href="https://giphy.com/"><em>https://giphy.com/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bbf335eeaec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Injection using Koin]]></title>
            <link>https://sreeharikv112.medium.com/dependency-injection-using-koin-4de4a3494cbe?source=rss-500a950c8175------2</link>
            <guid isPermaLink="false">https://medium.com/p/4de4a3494cbe</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[koin]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mobile]]></category>
            <dc:creator><![CDATA[Sreehari Vasudevan]]></dc:creator>
            <pubDate>Sat, 14 Mar 2020 18:16:22 GMT</pubDate>
            <atom:updated>2022-11-21T08:03:46.694Z</atom:updated>
            <content:encoded><![CDATA[<p>Koin is the dependency injection framework purely built in Kotlin. Comparing to Dagger2, we can find many features which are developer friendly in Koin. Learning curve for <strong>Koin</strong> is less comparing with <strong>Dagger2</strong> 😊 . There are many features which are debatable. As Koin is newbie and still growing, it would be unfair to compare with the <strong>giant</strong>!. Lets go through the implementation details of Koin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u9NhU1H30tCpf3_X" /><figcaption>Photo by <a href="https://unsplash.com/@stereophototyp?utm_source=medium&amp;utm_medium=referral">Sara Kurfeß</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Koin as per <a href="https://insert-koin.io/">official docs</a> , is <em>A pragmatic lightweight dependency injection framework for Kotlin developers. Written in pure Kotlin using functional resolution only: no proxy, no code generation, no reflection!</em></p><p>Hmm.. 🤔 That’s sounds interesting, but does this really help a developer to focus on building application with ease? <strong>Los geht’s…</strong></p><p>For those who are impatient , full source code can be found in <a href="https://github.com/sreeharikv112/KoinDIExample">Github</a>.</p><p>Before proceeding, let’s get clarified how exactly does Dependency Injection(DI) helps development. DI is closely related to Single Responsibility Principle and Dependency Inversion.</p><ol><li>Single Responsibility Principle: Class / group of classes / module in a single program is responsible for specific functionality which resolves single problem.</li><li>Dependency Inversion: Upper level modules should not depend on lower level modules.</li></ol><p>If we follow these principles, program will have loosely coupled modules. Now lest see how to begin with!</p><p>Add dependencies in <a href="https://github.com/sreeharikv112/KoinDIExample/blob/master/app/build.gradle">build.gradle</a> with corresponding version</p><pre>dependencies {<br>   //Koin<br>   implementation &quot;org.koin:koin-android:$XX&quot;<br>   implementation &quot;org.koin:koin-androidx-viewmodel:$XX&quot;<br>}</pre><h4>Koin important keywords/functions</h4><ol><li>startKoin : Create and register KoinApplication instance</li><li>modules : Declare used modules</li><li>androidContext : Use given Android context</li><li>by inject() : allows to retrieve instances lazily</li><li>get() : function to retrieve directly an instance (non lazy)</li><li>koinComponent : For using koin features, tag the class with the same to get access to koin functions</li></ol><h4><strong>Koin Scopes</strong></h4><ol><li>single : creates an object that persistent with the entire container lifetime</li><li>factory : creates new object each time. No persistence in container</li><li>scoped: creates object that persist to associated scope lifetime</li></ol><p>All the dependencies needs to be Started in Application class with <em>startKoin</em> and providing Android context as per <a href="https://start.insert-koin.io/#/getting-started/koin-for-android">official documentation</a>.</p><pre>class MainApplication : Application(){</pre><pre>override fun onCreate() {<br>    super.onCreate()<br>    initKoin()<br>  }</pre><pre>private fun initKoin() {<br>    <em>startKoin </em>{<strong><br>        </strong><em>androidContext</em>(this@MainApplication)<br>        modules(provideDependency())<br>    }<strong><br>  </strong>}</pre><pre>//List of Koin dependencies<br>  open fun provideDependency() = <em>appComponent</em></pre><pre>}</pre><p>We would need to consider Android Context and list of modules for initiating <em>Koin</em>. Now lets create common list for dependencies (<em>appComponent</em>). You can add all the required dependencies over here. In order to start with, let us consider Network and Utility class as targeted dependencies. Once we understood the steps and procedure for <em>Koin</em>, we can move on to more complicated dependencies. Altogether we will cover the following dependencies in this session.</p><pre>val appComponent = listOf(<br>    <em>NetworkDependency</em>,<br>    <em>AppUtilDependency</em>,<br>    <em>UseCaseDependency</em>,<br>    <em>viewModelDependency<br></em>...)</pre><p>For Network dependency , create <a href="https://github.com/sreeharikv112/KoinDIExample/blob/master/app/src/main/java/com/dev/koindiexample/dependencies/NetworkDI.kt"><em>NetworkDependency.kt</em></a> . As per Koin, all the dependencies should be described in individual <em>Koin</em> modules. For that , let us see how to create a <em>Koin</em> module. Then we will talk about how to start the same in Android. A typical module inculding Network dependency will be like the below.</p><h4><strong><em>Network Dependency</em></strong></h4><pre>val <em>NetworkDependency </em>= <em>module </em><strong>{<br><br>    </strong>single <strong>{<br>     </strong>Retrofit.Builder().addConverterFactory<br>     (GsonConverterFactory.create<br>     (GsonBuilder().create()))<br>     .addCallAdapterFactory<br>     (CoroutineCallAdapterFactory())<br>     .baseUrl(BuildConfig.<em>BASE_URL</em>).build()<br>    <strong>}<br>    </strong>single <strong>{ </strong>get&lt;Retrofit&gt;().create(SampleService::class.<em>java</em>)<strong>}</strong><br><strong>}</strong></pre><p>Don’t be panic, let me explain the details. As shown above, we will pass the required minimal details of Retrofit instance to be created. For instance, we need json converter to parse the response =&gt; <em>GsonConverter. </em>Next we need caller adapter factory. If using coroutines, we can use=&gt; <em>CoroutineCallAdapterFactory</em>. If using Rx , then =&gt; <em>RxJava2CallAdapterFactory</em> can be used instead of coroutine one. Next goes the =&gt; base url for initial configuration. And then we need to tell the corresponding =&gt; API service required for Retrofit. In this case its the <em>SampleService.kt</em>. Being said that, the sample network service can be as follows.</p><pre>interface SampleService{       <br> @GET(&quot;loginapi/&quot;)                           <br> suspend fun getRemoteData(@Query(&quot;parameter&quot;) param:String)<br>                                   :DemoDataClass                                              <br>}</pre><p>With this, our Network Dependency is ready to rock! 😊</p><h4>Utility Class</h4><p>And next, let us cover the Utility class. In some cases , we require context in multiple methods. So to create the Utility class, we will need the context as a mandatory input, so that any method will be able to proceed with the same. Let us see how to create the same.</p><pre>class AppUtility(var context: Context) {</pre><pre>  //Use the context object as common reusable throughout methods.</pre><pre>  //Utility method which needs context <br>  fun utilityMethodOne(){</pre><pre><br>  }</pre><pre>}</pre><p>Now for creating utility <em>Koin </em>dependency, the below will be the way. This will provide the context as well to the class while wiring the dependency. Koin will take care of setting up the context during the DI set up. We dont need to setup any explicit context. Simple isn&#39;t it! 😊</p><pre>val <em>AppUtilDependency </em>= <em>module </em><strong>{<br><br>    </strong>single <strong>{ </strong>AppUtility(<em>androidContext</em>()) <strong>}<br>}</strong></pre><h4>UI (Base Fragment)</h4><p>In-order to inject AppUtils in a <em>Fragment</em>, we can do the following.</p><pre>class BaseFragment : Fragment(){</pre><pre>   //Inject the app utility in base fragment<br>   val mAppUtils: AppUtility by <em>inject</em>()<br>}</pre><p>Now, as Utility is available in BaseFragment, other sub Fragments can access the app utility instance and methods.</p><p>Let us move on to classes which does not come under User Interface related classes. If any dependencies needed to be used in <strong>non UI related classes</strong>, we can use <em>KoinComponent</em>. As per Koin docs, you can find the below.</p><blockquote>Once you have tagged your class as KoinComponent, you gain access to:</blockquote><blockquote>by inject() - lazy evaluated instance from Koin container</blockquote><blockquote>get() - eager fetch instance from Koin container</blockquote><blockquote>getProperty()/setProperty() - get/set property</blockquote><p><a href="https://doc.insert-koin.io/#/koin-core/koin-component?id=unlock-the-koin-api-with-koincomponents">Koin - a pragmatic lightweight dependency injection framework for Kotlin</a></p><h4>Use Case</h4><p>For Use Cases (<a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">as per Clean Code Architecture</a>), we can have a base use case interface, which extends KoinComponent.</p><pre>interface BaseUseCase : KoinComponent</pre><p>Now for the specific use cases, extend this BaseUseCase class. As you can see, we are able to inject Utility cos of <em>KoinComponent</em> (inherited from BaseUseCase)</p><pre>class LandingUseCase : BaseUseCase {</pre><pre>   //Utility is available for usage in this class<br>   val mAppUtils: AppUtility by <em>inject</em>()<br>  <br>   fun someFunction(){<br>   }</pre><pre>}</pre><p>And now, we have to create koin dependency which can be initiated along with other dependencies.</p><pre>val <em>UseCaseDependency </em>= <em>module </em><strong>{<br>    </strong>factory <strong>{<br>        </strong>LandingUseCase()<br>    <strong>}<br></strong>}</pre><h4>View Model</h4><p>For View models, we will create an abstract BaseViewModel , which will extend AndroidViewModel and KoinComponent</p><pre>abstract class BaseViewModel(appContext:Application)<br>    : AndroidViewModel(appContext), KoinComponent</pre><p>Now, our LandingViewModel will inherit from BaseViewModel which requires a context to initiate. Hence we can create LandingViewModel as shown below.</p><pre>class LandingViewModel(context:Application) : BaseViewModel(context) {<br>  //Inject use case using Koin<br>  private val landingUseCase : LandingUseCase by <em>inject</em>()</pre><pre>  fun someFunction(){</pre><pre>  }</pre><pre>}</pre><p>Landing Use Case will be able to be injected with the same pattern. Next, create ViewModel dependency which can initiate VM by passing context in the constructor.</p><pre>val <em>viewModelDependency </em>= <em>module </em><strong>{<br><br>    </strong><em>viewModel </em><strong>{ </strong>LandingViewModel(<em>androidApplication</em>()) <strong>}<br>}</strong></pre><p>With all the explained layers and concepts, we can start integrating required dependencies into our Fragment.</p><pre>class LandingFragment : BaseFragment() {</pre><pre>  //View model injection using Koin way<br>  private val viewModel by <em>viewModel</em>&lt;LandingViewModel&gt;()<br>  <br>  //Utility is available for usage in this class<br>  val mAppUtils: AppUtility by <em>inject</em>()</pre><pre>  override fun onViewCreated(view: View, <br>    savedInstanceState:   Bundle?) {<br>    super.onViewCreated(view, savedInstanceState)<br><br>    btnTwo.setOnClickListener <strong>{<br>        </strong>viewModel.someFunction()<br>    <strong>}<br>   </strong>}</pre><pre>}</pre><p>As you can see, invoking a function in <a href="https://github.com/sreeharikv112/KoinDIExample/blob/master/app/src/main/java/com/dev/koindiexample/scenes/mainflow/landviewmodel/LandingViewModel.kt">View Model</a> (got using dependency injection) from <a href="https://github.com/sreeharikv112/KoinDIExample/blob/master/app/src/main/java/com/dev/koindiexample/scenes/mainflow/LandingFragment.kt">Fragment</a> is fairly simple. And View Model’s method inturn invoking <a href="https://github.com/sreeharikv112/KoinDIExample/blob/master/app/src/main/java/com/dev/koindiexample/scenes/mainflow/usecase/LandingUseCase.kt">Use Case</a> function as well.</p><p>Similarly you can try out including the other layers in <a href="https://medium.com/@sreeharikv112/android-unit-testing-clean-code-architecture-with-mvvm-73eb2992cab7">Clean Code Architecture</a> as well.</p><p>We have covered the dependency injection use cases in both UI and other classes which will be used in usual scenarios. Hope this helps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*ZQBlmtDa99tt1_4gD6dGrQ.gif" /></figure><h4><a href="https://doc.insert-koin.io/#/koin-android/fragment-factory">Further read</a></h4><p>For androidx.fragment , since 2.1.0-alpha-3 version FragmentFactory has got introduced to create instance of Fragment class. At start in KoinApplication declaration, use fragmentFactory() keyword to setup default KoinFragmentFactory instance.</p><pre>startKoin {<br>    androidLogger(Level.DEBUG)<br>    androidContext(this@MainApplication)<br>    androidFileProperties()<br>    // setup a KoinFragmentFactory instance<br>    fragmentFactory()<br><br>    modules(...)<br>}</pre><p>To declare Fragment instance, declare it as fragment in Koin module and use constructor injection</p><pre>class MyFragment(val myService: MyService) : Fragment() {<br><br><br>}</pre><pre>val appModule = module {<br>    single { MyService() }<br>    fragment { MyFragment(get()) }<br>}</pre><p>For host activity, setup fragment factory with setupKoinFragmentFactory()</p><pre>class MyActivity : AppCompatActivity() {<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        // Koin Fragment Factory<br>        setupKoinFragmentFactory()<br><br>        super.onCreate(savedInstanceState)<br>        //...<br>    }<br>}</pre><p>Further read portion is from official docs, More details can be found over <a href="https://doc.insert-koin.io/#/koin-android/fragment-factory">here</a></p><p>Full source code can be found in <a href="https://github.com/sreeharikv112/KoinDIExample">Github here</a>.</p><p><strong>Do clap 👏 if you find this article helpful</strong>.</p><p>Thanks for Reading ! Happy Coding Cheers 🤜🤛🥂 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4de4a3494cbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Communication from WebView to Native iOS/ Android App]]></title>
            <link>https://sreeharikv112.medium.com/communication-from-webview-to-native-ios-android-app-6d842cefe02d?source=rss-500a950c8175------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d842cefe02d</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[webview]]></category>
            <category><![CDATA[data-transfer]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sreehari Vasudevan]]></dc:creator>
            <pubDate>Sat, 01 Feb 2020 15:23:32 GMT</pubDate>
            <atom:updated>2020-02-01T17:56:31.428Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the most common use case in native mobile apps development is sending and receiving data from WebView to native and vice versa. There are couple of misconception while handling this scenario in iOS / Android. Let us deep dive into reality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ggKjiMk5n8i2hGwS" /><figcaption>Photo by <a href="https://unsplash.com/@_everaldo?utm_source=medium&amp;utm_medium=referral">Everaldo Coelho</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Many mobile applications have common features like login with third party vendor in which, native layer should interact with embedded webview. Or payment gateways which sends back success/failure/token etc to native to proceed. Which ever the scenario , interaction between native layer and webview is essential.</p><h4>Point #1:</h4><p>Is it really hard to make the flow functional while receiving callbacks from WebView to Native layer? 💻 🤔</p><h4>Point #2:</h4><p>Is sending data from Native to WebView or other way around a mess?🤔</p><p>But the fact is , both platforms provide convenient way for this type of communication. This tutorial shows how to achieve this in iOS and Android. For demonstration , I have included webview in both samples with a green background with input field and button. Similarly native has input field and button in white background. Data send from native will replace input field in web and vice-versa.🧐</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*I34tIOBlNVodrJvL3PTioA.gif" /><figcaption>Send and receiving data from native IOS to webview</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*ArnSuiAQmFnYt-R9SDxlOA.gif" /><figcaption>Send and receiving data from native Android to webview</figcaption></figure><p>Either load an Html page, which will be sent from server to mobile , or load a common Html file saved in app cache. For demonstration , lets have Html file in both platforms saved locally and loaded in WebView.</p><p>Respective Sources: <a href="https://github.com/sreeharikv112/WebViewNativeCommIos">iOS Github Source</a> and <a href="https://github.com/sreeharikv112/WebViewNativeComm">Android Github Source</a></p><h3><strong>1 — iOS:</strong></h3><p><strong>1.1</strong> To receive data from webview.We will use <em>WKScriptMessageHandler</em> protocol. This will help us to add script message handler from native with specific name of the message handler.</p><pre>var mNativeToWebHandler : String = “jsMessageHandler”</pre><pre>mWebKitView.configuration.userContentController.add(self, name: mNativeToWebHandler)</pre><p>After this, we can use the function <em>userContentController</em> to track specific handler.</p><pre>func userContentController(<strong>_</strong> userContentController: WKUserContentController, didReceive message: WKScriptMessage) {</pre><pre>if message.name == mNativeToWebHandler {</pre><pre>mEdtTxt.text = message.body as? String</pre><pre>}}</pre><p>Now we need to have function in HTML JS Script to send the data from HTML page. Which will be like the below. Keep the name of message handler as same in JS Script as well.</p><pre>function sendMessage(){</pre><pre>var valueToSend = //your data from html</pre><pre>window.webkit.messageHandlers.jsMessageHandler.postMessage(valueToSend);</pre><pre>}</pre><p><strong>1.2</strong> For sending data from Native to WebView, we can use <em>WKWebView</em>’s <em>evaluateJavaScript</em> method from native.</p><pre>var data = //your data from native</pre><pre>self.mWebKitView.evaluateJavaScript(“document.getElementById(‘inputField’).value=’\(data)’”)</pre><p>And the HTML component will be</p><pre>&lt;input id=&quot;inputField&quot; style=&quot;height:50px;width:300px;font-size:20pt;&quot; type=&quot;text&quot; value=&quot;&quot;&gt;</pre><p>This will directly replace the corresponding element in webview.😊👏 🎉</p><h3>2 — Android:</h3><p><strong>2.1</strong> To receive data from webview ,we can create an interface, which will enable webview to connect the native layer and pass data.</p><pre>function sendMessage() {<br>   var valueReceived =  document.getElementById(&quot;inputField&quot;).value;<br>      JSBridge.showMessageInNative(valueReceived);<br>  }</pre><pre>&lt;input id=&quot;inputField&quot; style=&quot;height:50px;width:300px;font-size:20pt;&quot; type=&quot;text&quot; value=&quot;&quot;&gt;</pre><p>From native layer, create a class and replicate the following.</p><pre>class JSBridge(){<br>    @JavascriptInterface<br>    fun showMessageInNative(message:String){</pre><pre>        //Received message from webview in native, process data</pre><pre>    }<br>}</pre><p>While configuring web view, we need to set JavaScript interface as above JSBridge class.</p><pre>mWebViewComponent.<em>settings</em>.<em>javaScriptEnabled </em>= true<br>mWebViewComponent.addJavascriptInterface(JSBridge(),&quot;JSBridge&quot;)</pre><p>Considering security:</p><p>If we are loading webpages which are known to our ecosystem, this wont have any issues wrt security. If this is not , opening interface and allowing WebView to communicate with native can be dangerous.🧐</p><p>As per <a href="https://developer.android.com/guide/webapps/webview">Android API documentation</a>:</p><blockquote>When the HTML in the WebView is untrustworthy (for example, part or all of the HTML is provided by an unknown person or process), then an attacker can include HTML that executes your client-side code and possibly any code of the attacker’s choosing. As such, you should not use addJavascriptInterface() unless you wrote all of the HTML and JavaScript that appears in your WebView. You should also not allow the user to navigate to other web pages that are not your own, within your WebView. Instead, allow the user’s default browser application to open foreign links.</blockquote><p><strong>2.1</strong> To send data from native layer to Webview.</p><p>Create a function in JavaScript to receive data in Html. Which will update inputField with the value received.</p><pre>function updateFromNative(message){<br>       document.getElementById(&quot;inputField&quot;).value = message;<br>  }</pre><pre>&lt;input id=&quot;inputField&quot; style=&quot;height:50px;width:300px;font-size:20pt;&quot; type=&quot;text&quot; value=&quot;&quot;&gt;</pre><p>Now from native layer, we can access this function by the following.😊👏 🎉</p><pre>private fun sendDataToWebView(){<br>    mWebViewComponent.evaluateJavascript(<br>        &quot;javascript: &quot; +&quot;updateFromNative(\&quot;&quot; + mEditText.<em>text </em>+  <br>                                                       &quot;\&quot;)&quot;,null)<br>    }</pre><p>And that&#39;s it, both the platforms are covered 😊👏 🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*jF7QmwWgXlKb0qwvFOspYA.gif" /></figure><p><strong>Now as you got the clear picture of Native and WebView communication, do have a trial and checkout how the same works in both platforms!</strong> 😇</p><p><a href="https://github.com/sreeharikv112/WebViewNativeComm">Full source code of Android sample can be found in Github over here</a></p><p><a href="https://github.com/sreeharikv112/WebViewNativeCommIos">Complete source of iOS sample can be found in Github over here</a></p><p>Do clap if you find this article helpful👏👏</p><p>Thanks for reading. Happy Coding! 🥳 Cheers! 🤜 🤛 🥂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d842cefe02d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST API with SpringBoot (Kotlin / Java)]]></title>
            <link>https://sreeharikv112.medium.com/rest-api-with-springboot-kotlin-java-f01216fd25a1?source=rss-500a950c8175------2</link>
            <guid isPermaLink="false">https://medium.com/p/f01216fd25a1</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[web-services]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Sreehari Vasudevan]]></dc:creator>
            <pubDate>Sat, 04 Jan 2020 17:59:02 GMT</pubDate>
            <atom:updated>2020-01-04T18:29:00.144Z</atom:updated>
            <content:encoded><![CDATA[<p>REST API which are used to connect between different entities in software world , can be created with multiple solutions. This is required to connect different Micro Services / Frontend with Backend / Desktop Solutions with Remote server / Mobile App with Backend etc. I found REST API creation with SpringBoot as much more interesting 😇 With <a href="https://www.jetbrains.com/help/idea/spring-boot.html">IntelliJ</a> OR <a href="https://start.spring.io/">Spring Initializer</a> and <a href="https://spring.io/tools3/sts/all">Spring Tool Suit</a> 💪 💻</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FlVHRFOEXOTfucjP" /><figcaption>Photo by <a href="https://unsplash.com/@mangofantasy?utm_source=medium&amp;utm_medium=referral">Tim Johnson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Prerequisite: Kotlin / Java. Either way the outcome will be the same.</p><p>Full source code can be found in <a href="https://github.com/sreeharikv112/springbootrestapikt">GithubKotlinProject</a> and <a href="https://github.com/sreeharikv112/RestAPISpringBoot">GithubJavaProject</a></p><p>This article is targeted to explain steps of REST API creation with Kotlin/Java and <a href="https://www.jetbrains.com/help/idea/spring-boot.html">IntelliJ</a>. So let’s start!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/1*KPeOYAu_4c3urE4NW2P_4A.png" /></figure><p>Launch IntelliJ and click on Create New Project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*YgUTdz9Iy73ABhZnUpZGhg.png" /></figure><p>Select Spring Initialzr , choose Default option as shown and click next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*HysDt7Gwxiy2HWB716qFTw.png" /></figure><p>Give the Group / Artifact / Select Language / Name / Description and Package as per your preference. Click Next button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*xI_5Ql9LT3RMC1ag3FSI8w.png" /></figure><p>Search for Dependency required. And select Spring Web. Selected Dependency will show <strong>Spring Web</strong>. Click Next.If more dependencies are required, you can search and add over here. If database is required, you can select JPA. Then add Spring Data JPA and other related dependencies as well.Any new dependency required can be added later on in <strong>pom.xml</strong>. As this Article is intended to explain only creation of REST without any database dependency, I will select only web as of now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*2IaHwgYiIr4C1GCmg4Xdog.png" /></figure><p>Select required project location. Click Finish.</p><p>Expand your source package,<em> src/main/kotlin/package_name</em>. You can see class named SpringbootrestapiktApplication.kt</p><pre><em>@SpringBootApplication</em><br>class SpringbootrestapiktApplication<br><br>fun main(args: Array&lt;String&gt;) {<br>    <em>runApplication</em>&lt;SpringbootrestapiktApplication&gt;(*args)<br>}</pre><p>As per <a href="https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/SpringBootApplication.html">Spring docs</a>, this indicates a configuration class that declares one or more @Bean methods and also triggers auto-configuration and component scanning. This is a convenience annotation that is equivalent to declaring @Configuration, @EnableAutoConfiguration and @ComponentScan.</p><p>Create a new RestController named <strong>StudentResource.java</strong> under new folder <strong>controllers</strong>. Annotate this class with <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RestController.html">@RestController</a> to indicate this is a controller. Now this class can have different mappings, which can be invoked from outerworld with valid parameters and semantics. 🤔</p><h4>Basically controller classes are interfaces to outer world which can accept requests. Which in-turn validates the request parameters, process corresponding business logic and get back data with help of other inter related components. 😎</h4><p>Majorly used request mappings are <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html">@GetMapping, @PostMapping, @DeleteMapping, @PutMapping</a>.</p><pre>@RestController<br>class StudentResource {<br><br>    @Autowired<br>    val studentsRepo = StudentsRepo()<br>}</pre><p>Create Repository class named StudentsRepo. Annotate this class with <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/stereotype/Repository.html">@Respository</a>. Ideally this class will have connection to database using <a href="https://spring.io/projects/spring-data-jpa">JPA</a>. But as this article does not cover database part, we will have local objects to store and manipulate list of objects. We will use <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Autowired.html">Autowired</a> annotation to inject repo dependency using Spring dependency injection facilities.</p><pre><em>@Repository<br></em>public class StudentsRepo {<br>   <br>       var mAllStudents = <em>mutableListOf</em>&lt;Student&gt;()<br><br>    init {<br>          val s1 = Student(&quot;Hari&quot;,24,&quot;Student Address 1&quot;)<br>          val s2 = Student(&quot;Sandy&quot;,33,&quot;Student Address 2&quot;)<br>          val s3 = Student(&quot;Jenny&quot;,12,&quot;Student Address 3&quot;)<br><br>          mAllStudents.add(s1)<br>          mAllStudents.add(s2)<br>          mAllStudents.add(s3)<br>        }</pre><pre>}</pre><p>As shown here, we have pojo class <em>Student</em>. And <em>mAllStudents</em> will be holding all objects manipulated by outer world. For initial response, I have just created sample <em>Student</em> object and added to <em>mAllStudents</em> list. 😊</p><p>Now in-order to retrieve all students as a json response, we will create a new method getAllStudents. Annotate with <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/GetMapping.html">@GetMapping</a>. This will help us in retrieving the targeted data and get back as JSON response.</p><pre><em>@GetMapping</em>(“getallstudents”)<br>fun getAllStudents(): List&lt;Student&gt;{<br><br>    return studentsRepo.retrieveAllStudents()<br>}</pre><p>Corresponding method in Repo class will be the below , which will get back all students data.</p><pre>fun retrieveAllStudents(): List&lt;Student&gt;{<br>    return mAllStudents<br>}</pre><p>In-order to run our Spring project, Click on Run Green button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*qQsTLU6DyP-micq9JqaP7Q.png" /></figure><p>Our local server will be running in 8080 port, the url will be <a href="http://localhost:8080/">http://localhost:8080/</a> . 🧐</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*n8QnHLUlirJS1NX9uKLB2Q.png" /></figure><p>To see the port number, verify the port number from console window. As you can see, the port number is 8080. 👀</p><p>We can use any rest client to test the response. <a href="https://www.getpostman.com/">Postman</a> is widely used popular tool. We can also use <a href="https://install.advancedrestclient.com/install">Advanced Rest client</a> as well.</p><p>As you can see request <a href="http://localhost:8080/getallstudent">http://localhost:8080/getallstudent</a>s gets back valid JSON response. 💚 👏 🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*wGM3X4LqAPcv7oSSVQ0SuA.png" /><figcaption>End point showing success response.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*rD3O7LrqDR6fK5R1e1GuEw.gif" /></figure><p>For creating new Student , use <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/PostMapping.html">@PostMapping</a>. Create new method like following. Use RequestBody mapping for accepting JSON object as input. Which will be the Student object in JSON form.</p><pre><em>@PostMapping</em>(“/createStudent”)<br>fun createNewStudent(@RequestBody student:Student): List&lt;Student&gt;{<br><br>    return studentsRepo.addStudent(student)<br>}</pre><p>For demonstration , I am adding the new object to list in Repository class.</p><p>In REST client, use Method as <strong>POST</strong>. Use Request URL as <a href="http://localhost:8080/createStudent">http://localhost:8080/createStudent</a> . For giving input JSON, use Parameters section. Select Body. And give new Student data as input. Click on Send button. You can verify the respose code as 200 💚 👏🥳</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*z1cfjT2ocHgNgu3ZxICCNg.png" /><figcaption>POST method for new Student creation.</figcaption></figure><p>You can validate the newly created Student with previous End point.Which was this : <a href="http://localhost:8080/getallstudent">http://localhost:8080/getallstuden</a>ts</p><p>Similarly you can try out PutMapping , PatchMapping etc.</p><p>For demonstrating <strong>search</strong> and <strong>delete</strong>, I have created the following in <a href="https://github.com/sreeharikv112/springbootrestapikt/blob/master/src/main/kotlin/com/example/springbootrestapikt/controllers/StudentResource.kt">Controller</a>.</p><ol><li>Delete functionality using DeleteMapping</li><li>Search specific student using GetMapping</li></ol><p>Hope you found this article helpful. Thanks for reading. 😇</p><p>Full source code can be found in <a href="https://github.com/sreeharikv112/springbootrestapikt">GithubKotlinProject</a> and <a href="https://github.com/sreeharikv112/RestAPISpringBoot">GithubJavaProject</a></p><p>Do clap if you find this article helpful👏👏</p><p>Happy Coding! 🥳 Cheers! 🤜 🤛 🥂</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*15NR8E1cLAC-4o9-i6ovsg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f01216fd25a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Instrumentation testing with Clean Code Architecture and MVVM]]></title>
            <link>https://sreeharikv112.medium.com/android-instrumentation-testing-with-clean-code-architecture-and-mvvm-5df4615f0e4a?source=rss-500a950c8175------2</link>
            <guid isPermaLink="false">https://medium.com/p/5df4615f0e4a</guid>
            <category><![CDATA[instrumentation-testing]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Sreehari Vasudevan]]></dc:creator>
            <pubDate>Tue, 24 Dec 2019 09:12:10 GMT</pubDate>
            <atom:updated>2020-01-07T18:02:50.404Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android UI testing (Instrumentation) with Clean Code Architecture and MVVM</h3><p>This article is continuation of <a href="https://medium.com/@sreeharikv112/android-unit-testing-clean-code-architecture-with-mvvm-73eb2992cab7">Medium Article about Unit Testing</a> , which is covering the first part with necessary basics as well as detailed implementation of Unit testing. Please go through the article for in depth background of Unit Testing (Clean Code + MVVM).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*t5VlARcSGbsHWp_-LTYbPw.png" /><figcaption>Data Flow — MVVM with Clean Code Arch</figcaption></figure><p>As instrumentation testing is targeted to cover UI, this article will concentrate on testing View.🥳</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*zED_tSxXJsVrx9l_YNz3Kg.gif" /></figure><p><strong>Main Libraries Used</strong></p><ul><li>Coroutines 🚀 <a href="https://developer.android.com/kotlin/coroutines">https://developer.android.com/kotlin/coroutines</a></li><li>Retrofit 📲 <a href="https://square.github.io/retrofit/">https://square.github.io/retrofit/</a></li><li>MockWebServer 🎭 <a href="https://github.com/square/okhttp/tree/master/mockwebserver">https://github.com/square/okhttp/tree/master/mockwebserver</a></li><li>Koin (💉Dependency Injection) <a href="https://insert-koin.io/">https://insert-koin.io/</a></li><li>Kotlin 🥇</li></ul><p>Getting required dependencies👨‍💻</p><pre>//Mock Web Server<br>androidTestImplementation &quot;com.squareup.okhttp3:mockwebserver:$XX&quot;</pre><pre>//Koin for UI Testing<br>androidTestImplementation &quot;org.koin:koin-test:$XX&quot;</pre><pre>//Espresso<br>androidTestImplementation &quot;androidx.test.espresso:espresso-contrib:$XX&quot;</pre><p>Detailed dependencies can be found in <a href="https://github.com/sreeharikv112/CleanCodeMVVMTesting">Github Project</a></p><p>To begin with , save local JSON with expected response in <em>src/androidTest/assets</em> folder as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*GlQOy3DID2x1dVMKaSmbxA.png" /><figcaption>local json for UI testing</figcaption></figure><p>Now we have to create Custom Junit Runner for overriding default runner and configure Application class for required dependencies.</p><pre>class CustomInstrumentationRunner : AndroidJUnitRunner() {<br>    override fun newApplication(cl: ClassLoader, <br>                                className: String, <br>                                context: Context): Application {<br>        return super.newApplication(cl, <br>            TestMainApp::class.<em>java</em>.<em>name</em>, <br>            context)<br>    }<br>}</pre><p>Refer the Custom Runner in <a href="https://github.com/sreeharikv112/CleanCodeMVVMTesting/blob/master/app/build.gradle"><em>build.gradle</em></a> as shown below.</p><pre>android {<br>   defaultConfig {<br>   <br>      //......<br>      testInstrumentationRunner &quot;com.dev.ccodetest.app.CustomInstrumentationRunner&quot;<br>      //......</pre><pre>   }<br>}</pre><p>This will help in customizing the dependencies required by overriding Application class via the following.</p><pre>class TestMainApp : MainApp() {<br>    override fun provideDependency() = <em>listOf</em>&lt;Module&gt;()<br>}</pre><p>Include Koin dependencies to be used via Application class and specific for Instrumentation testing. This will help us to mock expected responses while testing individual data flow. Refer <a href="https://github.com/sreeharikv112/CleanCodeMVVMTesting/blob/master/app/src/androidTest/java/com/dev/ccodetest/di/MainAppInstrumentationDI.kt">MainAppInstrumentationDI.kt</a> for the other dependencies.</p><pre>fun generateTestAppComponent(baseApi: String)<br>        = <em>listOf</em>(<br>    <em>configureNetworkForInstrumentationTest</em>(baseApi),<br>    <em>UseCaseDependency</em>,<br>    <em>MockWebServerInstrumentationTest</em>,<br>    <em>RepoDependency<br></em>)</pre><p>As shown above, pass on the mockserver url to network dependency for testing. Similar to Unit Testing, we will have a base class for UI test cases with required configurations ( <a href="https://github.com/sreeharikv112/CleanCodeMVVMTesting/blob/master/app/src/androidTest/java/com/dev/ccodetest/base/BaseUITest.kt">BaseUITest.kt</a> )</p><p>Create test class and extend the same with BaseUITest. While creating test class, make sure to create under <em>androidTest</em> folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*J6jaAb22UrZpTQCiCuwyug.png" /></figure><p>Use <em>ActivityTestRule</em> to invoke the respective Activity.</p><pre>@Rule<br>@JvmField<br>var mActivityTestRule = ActivityTestRule(LoginActivity::class.<em>java</em>, true, false)</pre><p>Inject <em>LoginUseCase</em> and <em>MockWebServer</em> by the following, so that View will have corresponding dependencies while executing.</p><pre>//Inject login use case created with koin<br>val mLoginUseCase : LoginUseCase by <em>inject</em>()</pre><pre>//Inject Mockwebserver created with koin<br>val  mMockWebServer : MockWebServer by <em>inject</em>()</pre><p>Load Koin modules through the following</p><pre>@Before<br>fun start(){<br>    super.setUp()<br>     <em>loadKoinModules</em>(<em>generateTestAppComponent<br>         </em>(getMockWebServerUrl()).<br>            <em>toMutableList</em>())<br>}</pre><p>We can get required response from <em>MockWebServer</em> and the same can be used in assertions to verify test case result. In the sample test case, invoke the activity and check if <em>RecyclerView’s </em><strong>X</strong> element is having <strong>Y</strong> content or not ! This is done with the help of <a href="https://github.com/sreeharikv112/CleanCodeMVVMTesting/blob/master/app/src/androidTest/java/com/dev/ccodetest/helpers/RecyclerMatcher.kt">RecyclerMatcher.kt</a></p><pre>val mNameTestOne = &quot;Luke Skywalker&quot;<br>val mDOBTestOne = &quot;19BBY&quot;<br>val mNameTestTwo = &quot;Obi-Wan Kenobi&quot;<br>val mDOBTestTwo = &quot;57BBY&quot;</pre><pre>@Test<br>fun test_recyclerview_elements_for_expected_response() {</pre><pre>    mActivityTestRule.launchActivity(null)</pre><pre>    //Mocks the network request and get back the json response</pre><pre>    mockNetworkResponseWithFileContent(&quot;success_resp_list.json&quot;<br>           ,HttpURLConnection.<em>HTTP_OK</em>)</pre><pre>    //....</pre><pre>onView(withId(R.id.<em>landingListRecyclerView</em>))<br>    .check(<br>        matches(<br>            <em>recyclerItemAtPosition</em>(<br>                0,<br>                ViewMatchers.hasDescendant(withText(mNameTestOne))<br>            )))<br>}</pre><p>In the same lines, we can use <em>scrollToPosition</em> method from <em>espresso-contrib</em> to scroll to the last index. Then we can check if the text matches with expected value or not. Which will be like the following.</p><pre>onView(withId(R.id.<em>landingListRecyclerView</em>)).perform(<br>    RecyclerViewActions.scrollToPosition&lt;LoginRecyclerViewAdapter.<br>        LoginFragViewHolder&gt;(9))<br><br>     onView(withId(R.id.<em>landingListRecyclerView</em>))<br>        .check(matches(<em>recyclerItemAtPosition</em>(9<br>         ,ViewMatchers.hasDescendant(withText(mNameTestTwo)))))</pre><p>After running the test case, we can see our test case passed and gave us Green ✔️💚🕺🥳🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*astIRyDiPImcQ0OQREHokA.png" /><figcaption>UI Test case passed.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*Lh_iUvd2YyVG-hIlZ73Exg.gif" /></figure><p>This concludes both UT and Instrumentation test in Android.</p><p>Hope I have given enough input to have a clear picture on the challenging Clean Code Arch + MVVM + UT + UI testing.😉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*8QuYKbN2hIY4MMkTsdvtVg.gif" /></figure><h4>Do clap 👏 👏 if you find this article helpful.</h4><p>Thanks for reading. Cheers🥂🤜🤛 . Happy Coding 😀🎉</p><p>First Part of the article is <a href="https://medium.com/@sreeharikv112/android-unit-testing-clean-code-architecture-with-mvvm-73eb2992cab7">over here</a></p><p>Full source code can be found in <a href="https://github.com/sreeharikv112/CleanCodeMVVMTesting">Github</a>.</p><p><em>All gif images copyright </em><a href="https://giphy.com/"><em>https://giphy.com/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5df4615f0e4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Unit Testing Clean Code Architecture with MVVM]]></title>
            <link>https://sreeharikv112.medium.com/android-unit-testing-clean-code-architecture-with-mvvm-73eb2992cab7?source=rss-500a950c8175------2</link>
            <guid isPermaLink="false">https://medium.com/p/73eb2992cab7</guid>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[instrumented-unit-test]]></category>
            <dc:creator><![CDATA[Sreehari Vasudevan]]></dc:creator>
            <pubDate>Fri, 20 Dec 2019 10:16:23 GMT</pubDate>
            <atom:updated>2023-01-09T12:31:39.203Z</atom:updated>
            <content:encoded><![CDATA[<p>Unit testing Android Application while libraries getting upgraded and added into Android eco system is definitely a challenge.😱</p><p>Similar is the story with <strong>Android</strong> + <strong>MVVM </strong>+ Uncle Bob’s <strong>Clean Code Architecture</strong>.</p><p>This post is targeted to address <strong>data flow</strong> with Clean Code Architecture and MVVM along with testing (UT + UI aka Instrumentation Testing)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*Bvn69d08YZjSNkOa7BfUSQ.gif" /></figure><p><strong>Main Libraries Used</strong></p><ul><li>Coroutines 🚀 <a href="https://developer.android.com/kotlin/coroutines">https://developer.android.com/kotlin/coroutines</a></li><li>Retrofit 📲 <a href="https://square.github.io/retrofit/">https://square.github.io/retrofit/</a></li><li>MockWebServer 🎭 <a href="https://github.com/square/okhttp/tree/master/mockwebserver">https://github.com/square/okhttp/tree/master/mockwebserver</a></li><li>Koin (💉Dependency Injection) <a href="https://insert-koin.io/">https://insert-koin.io/</a></li><li>Kotlin 🥇(If reference is required,you are in the wrong article😉)</li></ul><p><strong>Full Source code can be found in this </strong><a href="https://github.com/sreeharikv112/CleanCodeMVVMTesting"><strong>Github Project</strong></a></p><p>Here I will be mainly targeting how to test the <strong>data flow</strong> with respect to different <strong>components</strong> in the app. Which are the following points. Anybody can easily adopt the following technique in apps. Even for complex apps, underlying idea can remain the same.😇</p><ol><li><strong>View Model</strong> ( or consider this as an Interactor from View. Responsible for taking inputs from View and delivering back the processed response)</li><li><strong>Use Case</strong> ( There can be one or multiple use case flows in single View Model. Handles specific data manipulation for a flow and connecting with Repository for the same)</li><li><strong>Repository</strong> ( Either connects to REST API or Data Base)</li></ol><p><strong>Note:</strong> REST API provided by <a href="https://swapi.dev/">https://swapi.dev</a> will be used in this article for showing sample data retrieval. Thanks to SWAPI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*8PtPvGWEuLNKkmTbZqLAdw.png" /></figure><p>The complete API documentation detail can be found over <a href="https://swapi.dev/documentation">https://swapi.dev/documentation</a></p><h4><strong>Application Architecture</strong></h4><p>Let us target to consider a common data flow.</p><p><em>User launches app. App hits a URL and get back data. With which View populates a List View.</em></p><p>From the <a href="https://developer.android.com/jetpack/docs/guide">Android Guide to app architecture</a> , slight change for use case can get added for the separation of concerns. Which will give us the following architecture diagram. This article will be discussing the development details of the below architecture along with testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*P9lktbO10V6D7yirmHVeNQ.png" /><figcaption>Clean Code Architecture with MVVM</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*hfGEP5i8C70cuaI2jG_boQ.png" /><figcaption>List View displaying data from SWAPI</figcaption></figure><p>Targeted screen/fragment, view will have corresponding View Model class instance incorporated through <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/lazy.html">Kotlin lazy</a>. A method in ViewModel(VM) will be invoked to initiate data retrieval with few/no parameters.</p><p>VM will have reference to the respective Use Case class passed from Fragment received through Dependency Injection. With this reference , VM will invoke method in Use Case to execute corresponding use case flow (Eg:- Login request).</p><p>Use case will receive this call, if any business logic needs to be performed, use case will handle and similarly ,with the help of Repository reference received via Dependency Injection, use case invokes method in repository for getting data.</p><p>Repository will in-turn get in touch with Network API ( Retrofit/ Any similar Networking Client) and retrieves the data. Or connect to local Data Base and retrieves data.</p><p><strong>NOTE</strong>: In this flow, nowhere we are having cyclic reference of other components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*EiCi-Q5eaBxiVXB_G8M1BA.gif" /></figure><p>Now, getting back to the data flow. Once Repository receives data, it will decide whether data needs to be saved in local DB (Eg:- Room ORM) or just get back to caller. If the data needs to be reverted back to caller, the same will get passed over to View through the above explained flow in reverse order😀. <a href="https://developer.android.com/kotlin/coroutines">Kotlin coroutines</a> makes this flow relatively simple with help of suspend functions as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*Fq-C7h8p0fvigwKUQpbTTg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*BoMYWN8nubR5imVm1cL2hw.png" /></figure><h4>Important dependencies for the project</h4><p><em>build.gradle</em> will have the following. Complete dependencies can be found in <a href="https://github.com/sreeharikv112/CleanCodeMVVMTesting"><strong>Github Project</strong></a></p><pre>//Koin<br>implementation &quot;org.koin:koin-android:$XX&quot;</pre><pre>//Retrofit<br>implementation &quot;com.squareup.retrofit2:retrofit:$XX&quot;</pre><pre>//Coroutines<br>implementation &quot;org.jetbrains.kotlinx:kotlinx-coroutines-android:$XX&quot;</pre><pre>//Material<br>implementation &quot;com.google.android.material:material:$XX&quot;</pre><pre>//Mockk<br>testImplementation &quot;io.mockk:mockk:$XX&quot;</pre><pre>//Koin Test<br>androidTestImplementation &quot;org.koin:koin-test:$XX&quot;</pre><pre>//Mockwebserver<br>androidTestImplementation &quot;com.squareup.okhttp3:mockwebserver:$XX&quot;</pre><h4><strong>Dependency Injection with Koin</strong></h4><p>First part is to get our Dependency Injection (DI) targets and corresponding classes ready to be injected.</p><ul><li>Network ( Retrofit)</li><li>View Model</li><li>Use Case</li><li>Repository</li></ul><p>All these dependencies will be injected to main application class as follows</p><h4><strong>MainApp.kt</strong></h4><pre>class MainApp : MultiDexApplication() {<br><br>    override fun onCreate() {<br>        super.onCreate()<br>        initiateKoin()<br>    }<br><br>    private fun initiateKoin() {<br>        <em>startKoin</em><strong>{<br>            </strong><em>androidContext</em>(this@MainApp)<br>            modules(provideDependency())<br>        <strong>}<br>    </strong>}<br><br>    open fun provideDependency() = <em>appComponent<br></em>}</pre><h4><strong>MainDIComponent.kt</strong></h4><p>Concludes all dependencies required throughout the application. (List of Koin Dependencies )</p><pre>val <em>appComponent </em>= <em>listOf</em>(<em>UseCaseDependency</em>, <em>AppUtilDependency</em>, <em>NetworkDependency</em>, <em>SharedPrefDependency</em>, <em>RepoDependency</em>)</pre><h4><strong>LoginActivityFragment.kt</strong></h4><p>In view , the View Model will be injected and used as follows.</p><pre>private val mViewModel : LoginActivityViewModel by <em>lazy <br></em><strong>{<br>    </strong>ViewModelProviders.of(this,mBaseViewModelFactory)<br>        .get(LoginActivityViewModel::class.<em>java</em>)    <br><strong>}</strong></pre><h4><strong>LoginActivityViewModel.kt</strong></h4><p><strong><em>View Model</em></strong> will have Use Case as dependent class received from corresponding Fragment. Which will invoke specific method as shown below.</p><pre>fun requestLoginActivityData(param:String) {<br>    if(mAllPeopleResponse.<em>value </em>== null){<br>        mUiScope.<em>launch </em><strong>{<br>          <br>          //.....<br>        <br>          </strong>val data = mIoScope.<em>async </em><strong>{<br>              </strong>return@async useCase.processLoginUseCase(param)<br>           <strong>}</strong>.await()</pre><pre>          //.....</pre><pre><strong>      }<br>    }<br>}</strong></pre><h4><strong>LoginUseCase.kt</strong></h4><p><strong><em>Use Case</em></strong> will pass on the incoming request to Repository and handle any business logic required once data gets back from Repository.</p><pre>suspend fun processLoginUseCase(query: String) : AllPeople {<br>   //Data manipulation required prior </pre><pre>   val response =  mLoginRepo.getLoginData(query)</pre><pre>   //Data manipulation after receiving response    <br>    return response<br>}</pre><h4>LoginRepository.kt</h4><p>Repository will initiate Network Request and get back data from REST End Point.</p><pre>suspend fun processDataFetchLogic(parameter:String): AllPeople{<br><br>    //Data manipulation prior to REST API request if required<br><br>    val dataReceived = mLoginAPIService.getLoginData(parameter)<br><br>    //Data manipulation post REST API request if required<br><br>    return dataReceived<br>}</pre><h4>LoginAPIService.kt</h4><pre>@GET(&quot;people/&quot;)<br>suspend fun getLoginData(@Query(&quot;page&quot;) page:String): AllPeople</pre><p>The data received will be send back to UseCase. UseCase, as mentioned earlier will handle any business logic required and revert back processed response to ViewModel. ViewModel will update the live data object, which will be observed by View class. View in turn updates the data correspondingly.</p><h3>Unit Testing</h3><p>So now, coming to testing. 😵 Questions which would arise are. 🤔</p><ol><li>What classes need to be tested.</li><li>How can dependencies be 💉injected for testing.</li><li>How response will be mocked? If then what libraries needed to be used.</li><li>How will the mocked response be accessible to test classes.</li><li>Do I need to check only flow till my business logic hits Retrofit classes or should I test Retrofit classes as well.</li></ol><p>As the post is concentrating on clean code +MVVM <strong>data flow testing</strong>, I will concentrate on data flow areas only to keep the article less complicated. Ideally all the written code should be tested. By following TDD (<em>Test Driven Development</em>) all other classes developed can be targeting for testing.<em> Moreover neither developer will implement logic that is not testable nor include any code which is not required to satisfy the requirements.</em></p><p><strong>First and foremost point.</strong></p><p><em>❌🛑 In the mentioned data flow ,no classes other than Fragment/Activity should have reference to view.❌🛑</em></p><p>Having references of view in ViewModel or other classes are not at all encouraged. Moreover this makes the code <strong>Non Testable</strong>.</p><ol><li>Getting the dependencies ready for testing</li></ol><p>In-order to override and get specific dependencies for testing, we can create similar dependencies in test folder and make it available for test classes through following method.</p><pre><em>startKoin</em><strong>{ </strong>modules( .....)<strong>}</strong></pre><p>Through <em>MainDIcomponentTest.kt</em> we can have custom network dependency, MockWebServer and others injected to test classes using Koin. Test classes can invoke this as well.</p><pre>fun configureTestAppComponent(baseApi: String)<br>        = <em>listOf</em>(<br>    <em>MockWebServerDIPTest</em>,<br>    <em>configureNetworkModuleForTest</em>(baseApi),<br>    <em>UseCaseDependency</em>,<br>    <em>RepoDependency<br>    </em>)</pre><p>The <em>NetworkDITest.kt</em> will provide network dependency were we can pass the URL while testing with MockWebServer specific endpoint.</p><pre>fun configureNetworkModuleForTest(baseApi: String)<br>        = <em>module</em><strong>{<br>    </strong>single <strong>{<br>        </strong>Retrofit.Builder()<br>            .baseUrl(baseApi)<br>            .addConverterFactory (GsonConverterFactory<br>            .create (GsonBuilder().create()))<br>            .addCallAdapterFactory(CoroutineCallAdapterFactory())<br>            .build()<br>    <strong>}<br>    </strong>factory<strong>{ </strong>get&lt;Retrofit&gt;().create(LoginAPIService::class.<em>java</em>) <strong>}<br>}</strong></pre><p>With these, our dependencies for Unit Testing is completed.</p><p>2. Testing Repository Class</p><p>For unit testing, we will create a classes for basic configuration’s. Each unit test class will extend this base class which intern will be extending <strong>KoinTest</strong> class. Refer <strong>BaseUTTest.kt</strong> for the details.</p><p>While requesting for REST API , we can get back mocked response using MockWebServer. This response will be received from locally saved json file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*aEpSDY4DQkyjqk7TnNDMug.png" /><figcaption>Json file for Unit Testing</figcaption></figure><pre>val mNextValue = &quot;https://swapi.co/api/people/?page=2&quot;<br>val mParam = &quot;1&quot;<br>val mCount = 87</pre><pre>@Test<br>fun test_login_repo_retrieves_expected_data() =  <em>runBlocking</em>&lt;Unit&gt;<strong>{<br><br>  </strong>mockNetworkResponseWithFileContent(&quot;success_resp_list.json&quot;,  HttpURLConnection.<em>HTTP_OK</em>)<br>  mRepo = LoginRepository()<br><br>  val dataReceived = mRepo.getLoginData(mParam)<br><br>  assertNotNull(dataReceived)<br>  assertEquals(dataReceived.count, mCount)<br>  assertEquals(dataReceived.next, mNextValue)<br><strong>}</strong></pre><p>Compare the expectation with received response (Assertion) . We can see that test is passed and UT gives us a ✔️ 😍 Hoorrraaayyyy 🎉🕺🏆</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*Mhx0jG2J_q9xOXgueju9pA.png" /><figcaption>Login Repository Test case passed.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*htt_QysrWWs1OKvpMh2rtg.gif" /></figure><p>3. Testing Use Case class</p><p>In the similar lines, we can target <em>LoginUseCase</em>’s <em>processLoginUseCase</em> method for testing.</p><pre>val mNextValue = &quot;https://swapi.co/api/people/?page=2&quot;<br>val mParam = &quot;1&quot;<br>val mCount = 87</pre><pre>@Test<br>fun test_login_use_case_returns_expected_value()= <em>runBlocking</em><strong>{<br><br>    </strong>mockNetworkResponseWithFileContent(&quot;success_resp_list.json&quot;, HttpURLConnection.<em>HTTP_OK</em>)<br>    mLoginUseCase = LoginUseCase()<br><br>    val dataReceived = mLoginUseCase.processLoginUseCase(mParam)<br><br>    assertNotNull(dataReceived)<br>    assertEquals(dataReceived.count, mCount)<br>    assertEquals(dataReceived.next, mNextValue)<br><strong>}</strong></pre><p>We can get this test case also passed and gives us ✔️ 😍</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*gTxo9dv3d3pdluRPsx5Lfw.png" /><figcaption>Login Use Case Test Pass</figcaption></figure><p>3. Testing View Model class</p><p>Here we will use <em>Mockk</em>’s libraries <em>coEvery</em> method for mocking the expected response. To initiate mockk use the following.</p><pre>MockKAnnotations.init(this)</pre><p>And now we can have our test case with the following. And run the test.</p><pre>val mParam = &quot;1&quot;<br>val mNextValue = &quot;https://swapi.co/api/people/?page=2&quot;</pre><pre>@Test<br>fun test_login_view_model_data_populates_expected_value(){<br><br>    mLoginActivityViewModel = LoginActivityViewModel<br>                  (mDispatcher,mDispatcher,mLoginUseCase)<br>    val sampleResponse = getJson(&quot;success_resp_list.json&quot;)<br>    var jsonObj = Gson().fromJson(sampleResponse, <br>                  AllPeople::class.<em>java</em>)<br>    //Make sure login use case returns expected response when called<br>    <em>coEvery </em><strong>{ </strong>mLoginUseCase.processLoginUseCase(any()) <strong>} <br>             </strong>returns jsonObj<br>    mLoginActivityViewModel.mAllPeopleResponse.observeForever <strong>{}<br><br>    </strong>mLoginActivityViewModel.requestLoginActivityData(mParam)<br>    <br>    <em>assert</em>(mLoginActivityViewModel.mAllPeopleResponse.<em>value </em>!= null)<br>    <em>assert</em>(mLoginActivityViewModel.mAllPeopleResponse.<em>value</em>!!.<br>             responseStatus == LiveDataWrapper.<br>                             RESPONSESTATUS.SUCCESS)<br>    val testResult = mLoginActivityViewModel.mAllPeopleResponse<br>          .<em>value </em>as LiveDataWrapper&lt;AllPeople&gt;<br>    assertEquals(testResult.response!!.next,mNextValue)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*5vrj_wbAJtFFg0RegkgKeQ.png" /><figcaption>View Model test case passed</figcaption></figure><p>This completes <strong>testing the data flow</strong> of Clean Code Architecture.</p><p>I have kept the architecture as simple as possible for a beginner to grasp and start with. There are improvements and abstraction possible in many areas, which you can try out😉</p><p>With this I will give a pause and continue Instrumentation testing part in next post !</p><p>Part 2 : <a href="https://medium.com/@sreeharikv112/android-instrumentation-testing-with-clean-code-architecture-and-mvvm-5df4615f0e4a">Instrumentation Testing Clean Code + MVVM</a></p><p><strong>Do clap 👏 if you find this article helpful</strong>.</p><p><strong>Full Source code can be found in this </strong><a href="https://github.com/sreeharikv112/CleanCodeMVVMTesting"><strong>Github Project</strong></a></p><p>Thanks for Reading ! Happy Coding 🎉Cheers 🤜🤛🥂</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ZJyJVK9O7x1m6J1T4Z1JGA.gif" /></figure><p><em>All gif images copyright </em><a href="https://giphy.com/"><em>https://giphy.com/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73eb2992cab7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>