ocamlocaml-lwtmirage

Putting lwt.t code in infinite loop in Ocaml for mirage os


I have the following code block which I modified from the mirageOS github repo:

open Lwt.Infix

module Main (KV: Mirage_kv.RO) = struct

  let start kv =
    let read_from_file kv =
        KV.get kv (Mirage_kv.Key.v "secret") >|= function
            | Error e ->
                Logs.warn (fun f -> f "Could not compare the secret against a known constant: %a"
                KV.pp_error e)
            | Ok stored_secret ->
                Logs.info (fun f -> f "Data -> %a" Format.pp_print_string stored_secret);
               
    in
        read_from_file kv
end

This code reads data from a file called "secret" and outputs it once. I want to read the file and output from it constantly with sleep in between.

The usage case is this: While this program is running I will update the secret file with other processes, so I want to see the change in the output.

What I tried ?

I tried to put the last statement in while loop with

in 
   while true do 
   read_from_file kv
   done

But It gives the error This expression has type unit Lwt.t but an expression was expected of type unit because it is in the body of a while loop.

I just know that lwt is a threading library but I'm not a ocaml developer and don't try to be one, (I'm interested in MirageOS) , so I can't find the functional syntax to write it.


Solution

  • You need to write the loop as a function. e.g.

    let rec loop () =
      read_from_file kv >>= fun () ->
      (* wait here? *)
      loop ()
    in
    loop ()